例如我有一个文件“input.txt”:
This is the
first data
This is the second
data
This is the last data
on the last line
我想以这种形式将这些数据存储在 ArrayList 中:
[This is the first data, This is the second data, This is the last data on the last line]
注意:文件中的每个数据都用空行分隔。如何跳过这个空行?我尝试了这段代码,但它不能正常工作:
List<String> list = new ArrayList<>();
File file = new File("input.txt");
StringBuilder stringBuilder = new StringBuilder();
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
String line = in.nextLine();
if (!line.trim().isEmpty())
stringBuilder.append(line).append(" ");
else {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
}
} catch (FileNotFoundException e) {
System.out.println("Not found file: " + file);
}