无法读取文件的最后一行,未输入循环

Cannot read last line of file, loop is not entered

提问人:user12192927 提问时间:4/15/2020 最后编辑:user12192927 更新时间:4/15/2020 访问量:367

问:

我正在尝试将.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 文件的每一行都以新行结束,并且不包含尾随空格。 谢谢!

java io java.util.scanner bufferedreader

评论

0赞 Ralf Renz 4/15/2020
如果在 while 循环中删除 !line.isEmpty() 会发生什么?
0赞 user12192927 4/15/2020
@RalfRenz什么都没有改变
0赞 Joachim Sauer 4/15/2020
你正在尝试读取一个文件,但你读了.你如何运行你的代码?另外:不要在同一个底层 () 上同时打开 a a,这必然会导致问题。System.inScannerInputStreamReaderInputStreamSystem.in
0赞 user12192927 4/15/2020
@JoachimSauer我通过命令行参数运行文本文件。由于我使用eclipse,我将运行配置设置为接收“test.txt”,这是我的文件。另外,是的,我在运行缓冲阅读器时忘了注释掉该行,但它似乎没有任何改善。

答:

0赞 nic 4/15/2020 #1

您需要一个 EOF 字符才能终止程序。尝试在控制台中键入 CTRL-D,这将结束执行。

评论

0赞 user12192927 4/15/2020
什么算作 EOF 角色?为什么它不能读取最后一行?谢谢
0赞 nic 4/15/2020
我不确定你还不清楚什么。请检查 en.wikipedia.org/wiki/End-of-file。我测试了您的方法,它对我有用,我只需要键入 CTRL-D 并弹出最后一行。