【发布时间】:2020-04-15 07:52:48
【问题描述】:
我正在尝试将 .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文件的sn-p:
...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,在该场景中我 not 以空行结束文本文件。
.txt 文件的每一行也以新行结尾,并且不包含尾随空格。 谢谢!
【问题讨论】:
-
如果在 while 循环中删除 !line.isEmpty() 会发生什么?
-
@RalfRenz 没有任何变化
-
您说您正在尝试读取文件,但您读取了
System.in。你如何运行你的代码?另外:不要在同一底层InputStream(System.in) 上打开 bothScanner和InputStreamReader,这势必会导致问题。 -
@JoachimSauer 我正在通过命令行参数运行文本文件。由于我使用 Eclipse,我将运行配置设置为接收“test.txt”,这是我的文件。另外,是的,我在运行缓冲阅读器时忘记注释掉该行,但它似乎没有任何改进。
标签: java io java.util.scanner bufferedreader