首页 > 解决方案 > 无法读取文件的最后一行,未进入循环

问题描述

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

标签: javaiojava.util.scannerbufferedreader

解决方案


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


推荐阅读