您根本不需要拆分任何字符串。您可以简单地读取一行并将其添加到 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]