【问题标题】:Java File IO - file must have blank line to be read correctlyJava File IO - 文件必须有空行才能正确读取
【发布时间】:2017-03-01 21:47:56
【问题描述】:

我正在编写一个文件 IO 方法,并且在 try/catch 子句中有一个 while 循环。因此,尽管我正在阅读的 txt 文件的末尾必须有一个新的空白行才能正常工作,但它仍然有效。如果 txt 文件没有这个空行,那么它会运行,但最后也会产生我的 catch 异常错误消息。

关于如何实现 NoSuchElementException 来解决此问题的任何想法。

谢谢

【问题讨论】:

  • 您尚未接受所有问题的任何答案。我认为你永远不会有一个可以接受的答案。

标签: java file-io exception-handling


【解决方案1】:

将while循环更改为:

while((line = reader.readLine()) != null){
    Sysout...
}

它会起作用的。 您的代码的问题是,您读取了一行,然后再次进入 whileloop。

【讨论】:

    【解决方案2】:
        Scanner in = new Scanner(filename);
    
        File fileName = new File(filename);
    
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
    
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
    
        } catch(Exception e) {
            System.out.println("ERROR FILE NOT FOUND");
            in.close(); // close scanner if file not found
        }
    

    【讨论】:

      【解决方案3】:

      替换

          String line = reader.readLine();
      
               while(line.length() > 0) {
                  System.out.println(line);
      
                  line = reader.readLine();
      
               }
      

               String s;
      
               while((s = reader.readLine()) != null) {
                  System.out.println(s);
               }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-14
        • 2014-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-05
        相关资源
        最近更新 更多