gpt4 book ai didi

java - 初始化 ObjectInputStream 会导致 IOException 类型的 EOFException

转载 作者:行者123 更新时间:2023-12-01 17:19:40 26 4
gpt4 key购买 nike

我一直在用 java 编写一个待办事项列表应用程序,每个待办事项都存储为 ToDo 类(我创建的)的对象。
ToDo 类是可序列化的,我使用 ObjectOutputStream 将对象写入文本文件。执行此操作后,我关闭了 ObjectOutputStream。
我可能应该提到,目前我的文本文件是空的,因为其中没有待办事项,并且 GUI.items 是我的 GUI 类中的静态 ArrayList。

当我运行读取文件的方法时,会抛出 IO 异常:

ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

这是读取文件的方法:

public void read() {
try (FileInputStream fileInputStream = new FileInputStream("todo.txt")) {

ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

GUI.items.clear();

while (objectInputStream.readObject() != null) {
GUI.items.add((ToDo) objectInputStream.readObject());
}

GUI.updateInterface();

objectInputStream.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
//JOptionPane.showMessageDialog(null, "Error: To-Do List not found.\nPlease contact the developer.", "Error", JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error: To-Do List could not be opened.\nPlease contact the developer.", "Error", JOptionPane.ERROR_MESSAGE);
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "Error: To-Do List object type could not be found.\nPlease contact the developer.", "Error", JOptionPane.ERROR_MESSAGE);
}
}

为什么会抛出此异常以及如何修复它?谢谢。

最佳答案

是的,这表现为 documented :

Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified.

...

Throws:
IOException - if an I/O error occurs while reading stream header

如果您的文件为空,则它不包含流 header 。使用 ObjectOutputStream 创建的文件在写入 0 个对象后已关闭,这与空文件不同。

关于java - 初始化 ObjectInputStream 会导致 IOException 类型的 EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19623328/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com