您的代码有多个问题,例如 @Henry 说您的字符串仅包含文件的最后一行,而且您误解了 split(),因为它需要 RegularExpression 作为参数。
我建议您使用以下示例,因为它有效并且比您的方法快得多。
启动示例:
// create a buffered reader that reads from the file
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
// create a new array to save the lists
ArrayList<String> lists = new ArrayList<>();
String list = ""; // initialize new empty list
String line; // initialize line variable
// read all lines until one becomes null (the end of the file)
while ((line = reader.readLine()) != null) {
// checks if the line only contains one *
if (line.matches("\\s*\\*\\s*")) {
// add the list to the array of lists
lists.add(list);
} else {
// add the current line to the list
list += line + "\r\n"; // add the line to the list plus a new line
}
}
说明
我将再次解释难以理解的特殊行。
看第一行:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
这一行创建了一个BufferedReader,它与Scanner 几乎相同,但它更快,并且没有Scanner 那么多的方法。对于这种用法,BufferedReader 绰绰有余。
然后它将InputStreamReader 作为构造函数中的参数。这只是将以下FileInputStream 转换为Reader。
为什么要这样做?那是因为InputStream≠Reader。 InputStream 返回原始值,Reader 将其转换为人类可读的字符。见the difference between InputStream and Reader。
看下一行:
ArrayList<String> lists = new ArrayList<>();
创建具有add() 和get(index) 等方法的变量数组。见the difference of arrays and lists。
最后一个:
list += line + "\r\n";
这一行将line 添加到当前列表中并在其中添加一个新行。
"\r\n" 是特殊字符。 \r 结束当前行,\n 创建一个新行。
您也可以只使用\n,但在它前面添加\r 会更好,因为它支持更多的操作系统,如Linux,当\r 未命中时可能会出现问题。
相关
Using BufferedReader to read Text File