java - 无法读取文件的最后一行,未进入循环
问题描述
我正在尝试将 .txt 文件读入 java。不管它是否以空行结束,阅读器都不会读到最后一行,程序也不会终止。
public static ArrayList<String> readInput() {
// TODO Auto-generated method stub
ArrayList<String> input = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
// while (scanner.hasNextLine()) {
// String line = scanner.nextLine();
// if (line.equals("") || line.isEmpty()) {
// break;
// }
// input.add(line);
// System.out.println(line);
// }
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
while((line = reader.readLine()) != null && !line.isEmpty()) {
input.add(line);
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
JOptionPane.showMessageDialog(null,"File not found or is unreadable.");
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//PROGRAM WILL NOT GO BEYOND THIS POINT.
JOptionPane.showMessageDialog(null,"File has finished reading.");
return input;
在这里,我尝试了两种方法。一个带有缓冲阅读器,另一个带有扫描仪,但都不起作用。这是 .txt 文件的片段:
...some more lines...
33
0 0 0
1 0 0
0 1 0
34
0 0 0
1 0 0
1 0 0
35
0 1 0
0 1 0
0 0 1
36
1 0 0
0 1 0
0 1 0
程序将读取到倒数第二行。所以这就是我所看到的:
...some lines...
0 0 1
36
1 0 0
0 1 0
并且程序仍将运行。它甚至不会重新进入 while 循环(我用 println 对其进行了测试)。
即使我要在最后一行之后添加一个空行,如下所示:
...some lines...
0 0 1
36
1 0 0
0 1 0
0 1 0
<a blank line>
程序将读到最后一行数字,无法重新进入循环,程序不会终止。
...some lines...
0 0 1
36
1 0 0
0 1 0
0 1 0
我尝试到处寻找解决方案,但似乎找不到真正解决此问题的解决方案。
最好,我想遵循方案 1,我不以空行结束文本文件。
.txt 文件的每一行也以新行结尾,并且不包含尾随空格。谢谢!
解决方案
您需要一个 EOF 字符才能终止您的程序。尝试在控制台中键入 CTRL-D,这将结束执行。
推荐阅读
- c# - C# 组合框 - “已删除的实体”?
- uwp - EntityFrameworkcore.sqlite 的主键数据注释不起作用
- java - Spring JPA @Query 注释,SQL 地理定位错误
- reactjs - Redux 状态不会根据输入而改变
- java - 替换硬编码凭据
- vba - In Word 2016 embedded Excel tables can't be scaled via VBA
- c# - 解决接口的多重实现
- informix - ifxnjs 不支持 NODE_MODULE_VERSION 64
- tfs - 给出“MsBuild.exe”的 SonarScanner 在 TFS 2018 上未被识别为内部或外部命令
- java - Hazelcast-wm 节点如何在 P2P 模式下找到彼此?