提问人:Vlad Gric 提问时间:12/6/2020 更新时间:12/6/2020 访问量:1349
如何从 Java 中用空行分隔的文件中读取数据
How read data from file that is separated by a blank line in Java
问:
例如,我有一个文件“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);
}
答:
1赞
Basil Bourque
12/6/2020
#1
空行并不是真正的空白。终止每行涉及行尾字符。明显的空行表示您有一对行尾字符相邻。
搜索该对,并在找到时断开您的输入。例如,使用类似 .String::split
例如,假设我们有一个包含单词 和 的文件。this
that
this
that
让我们可视化此文件,将用于终止每行的 LINE FEED (LF) 字符(Unicode 码位 10 十进制)显示为 。<LF>
this<LF>
<LF>
that<LF>
对于计算机来说,没有“行”,所以文本对 Java 来说是这样的:
this<LF><LF>that<LF>
现在,您可以更清楚地注意到成对的换行 (LF) 字符如何分隔每行。搜索该配对的实例以解析文本。
1赞
Agus
12/6/2020
#2
你实际上快到了。您错过的是最后 2 行需要以不同的方式处理,因为文件底部没有空字符串行。
try (Scanner in = new Scanner(file)) {
while (in.hasNext()) {
String line = in.nextLine();
//System.out.println(line);
if (!line.trim().isEmpty())
stringBuilder.append(line).append(" ");
else { //this is where new line happens -> store the combined string to arrayList
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
}
//Below is to handle the last line, as after the last line there is NO empty line
if (stringBuilder.length() != 0) {
list.add(stringBuilder.toString());
} //end if
for (int i=0; i< list.size(); i++) {
System.out.println(list.get(i));
} //end for
} catch (FileNotFoundException e) {
System.out.println("Not found file: " + file);
}
以上输出:
This is the first data
This is the second data
This is the last data on the last line
0赞
Saad Sahibjan
12/6/2020
#3
我在您的代码中的 while 循环之后添加了一个 if 编码,它起作用了,
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();
}
}
if (stringBuilder.toString().length() != 0) {
list.add(stringBuilder.toString());
}
} catch (FileNotFoundException e) {
System.out.println("Not found file: " + file);
}
System.out.println(list.toString());
我得到了以下输出
[This is the first data , This is the second data , This is the last data on the last line ]
评论