根据换行符分割文件

时间:2020-11-11 17:38:33

标签: java arrays string file split

我正在读取一个包含配方信息和说明的rcp文件,我想根据换行符对其进行拆分,以便将第1行拆分为[0],将第2行拆分为[1],依此类推,等等。
我所拥有的:

name

示例rcp文件:

FileInputStream file = new FileInputStream("file.rcp");
        BufferedReader reader = new BufferedReader(new InputStreamReader(file));
        
        String line = reader.readLine();
        
        while (line != null) {
            String [] split = line.split("\\r?\\n");
            String name = split[0]; // test to see if name will print the first line only
            System.out.println(name);
            line = reader.readLine();
        }

在这种情况下,Food name - gyros author - some name Cusine type - greek Directions - some directions Ingredients - some ingredients 仅在打印第一行时打印整个文件(在这种情况下,这是食物的名称)。
如果我尝试打印name,我会得到split[1]

2 个答案:

答案 0 :(得分:2)

文档(即readline()的Javadoc)说:

返回一个包含行内容的字符串,不包含任何行终止符

这意味着line.split("\\r?\\n")new String[] { line }相同,也就是说,这完全是没用的事情。

如果您想将整个文件作为行数组读取到内存中,只需调用Files.readAllLines()

List<String> linesList = Files.readAllLines(Paths.get("file.rcp"));
String[] linesArray = linesList.toArray(new String[0]);

答案 1 :(得分:0)

您根本不需要拆分任何字符串。您可以简单地读取一行并将其添加到List<String>(如果知道行数,则可以添加到数组)。

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        FileInputStream file = new FileInputStream("file.rcp");
        List<String> list = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file))) {
            String line = reader.readLine();
            while (line != null) {
                list.add(line);
                line = reader.readLine();
            }
        }

        System.out.println(list);

        // An array out of the list
        String[] arr = list.toArray(new String[0]);
        System.out.println(Arrays.toString(arr));
    }
}

输出:

[Food name - gyros, author - some name, Cusine type - greek, Directions - some directions, Ingredients - some ingredients]
[Food name - gyros, author - some name, Cusine type - greek, Directions - some directions, Ingredients - some ingredients]

如果您已经将文件的内容读为某个字符串(例如,如下所示的String fileContent),则可以简单地将字符串拆分到\r?\n上,这将产生一个String[]

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws IOException {
        String fileContent = new String(Files.readAllBytes(Paths.get("file.rcp")));
        // Java11 onwards
        // String fileContent = Files.readString(Path.of("file.rcp"));

        String[] arr = fileContent.split("\\r?\\n");
        System.out.println(Arrays.toString(arr));
    }
}

输出:

[Food name - gyros, author - some name, Cusine type - greek, Directions - some directions, Ingredients - some ingredients]
相关问题