【问题标题】:EOFException with ObjectInputStream带有 ObjectInputStream 的 EOFException
【发布时间】:2020-12-18 17:28:12
【问题描述】:

我已经阅读了与此类似的其他问题,但没有多大帮助。所以我在一个文件中有一些序列化的内容,我试图读取它并在控制台上打印它,内容打印得很好,但最后,它显示了一个 EOFException。有什么方法可以修复我的代码以避免此异常?

try {
            File file = new File("EnrolledStudentsSerial.txt");
 
            FileInputStream fi = new FileInputStream(file);
            ObjectInputStream input = new ObjectInputStream(fi);
            while(true) {
                System.out.println(input.readObject());
            }
        } 
        catch (IOException | ClassNotFoundException e) {
            System.out.println("Error: " + e); 
        }

【问题讨论】:

    标签: java netbeans deserialization objectinputstream eofexception


    【解决方案1】:

    我认为您不想“避免”此异常。

    您需要知道输入结束的时间,EOFException 是告诉您输入结束的原因。

    相反,您不想将其视为错误情况,因为它不是错误,而是正常且预期的。

    try {
       … code as before … 
    } 
    catch (EOFException e) {
       // end of input, nothing to do here
    }
    catch (IOException | ClassNotFoundException e) {
        System.out.println("Error: " + e); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 2018-05-23
      • 1970-01-01
      相关资源
      最近更新 更多