gpt4 book ai didi

java - 用这种方法创建新的 .ser 文件有什么问题?

转载 作者:太空宇宙 更新时间:2023-11-04 10:42:05 26 4
gpt4 key购买 nike

如果尚不存在对象,我正在尝试创建一个新的 .ser 文件来存储对象。运行时,它会抛出 EOFException。 EOFException 到底是什么?该方法是否正确编写以创建和读取 .ser 文件?感谢您的任何反馈。

public void readDatabase() throws IOException {

File dataFile = new File("database.ser");

// If data file does not exist, create it.
if (!dataFile.exists()) {
System.out.println("database.ser does not exist, creating one now . . .");
// if the file doesn't exists, create it
dataFile.createNewFile();
return; // No need to try to read anything from an empty file, so return.
}
ObjectInputStream objectinputstream = null;
boolean cont = true;
try {
FileInputStream streamIn = new FileInputStream(dataFile);
objectinputstream = new ObjectInputStream(streamIn);
while (cont) {
Item obj = null;
try {
obj = (Item) objectinputstream.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (obj != null)
itemList.add(obj);
else
cont = false;
}
} catch (FileNotFoundException e) {
e.printStackTrace();

} catch (IOException e) {
e.printStackTrace();
} finally {
if (objectinputstream != null) {
objectinputstream.close();
}
}

}

EOF异常:

java.io.EOFException
at java.base/java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2758)
at java.base/java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3253)
at java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)
at java.base/java.io.ObjectInputStream.<init>(ObjectInputStream.java:343)
at hardwarestore.HardwareStore.readDatabase(HardwareStore.java:254)
at hardwarestore.HardwareStore.<init>(HardwareStore.java:33)
at hardwarestore.MainApp.<init>(MainApp.java:24)
at hardwarestore.MainApp.main(MainApp.java:259)

最佳答案

EOFException代表:

End of File Exception

当您尝试从 FileReader 已到达文件末尾的文件中读取数据时,通常会发生这种情况。换句话说,没有更多数据可供读取。

您应该捕获异常并关闭流。因为它表明您已读取文件中的所有对象。引用answer in this question :

 while (true) {
try {
// Read the next object from the stream. If there is none, the
// EOFException will be thrown.

Item obj = (Item) objectinputstream.readObject();
itemList.add(obj);
} catch (EOFException e) {
// If there are no more objects to read, return what we have.
return contactMap;
} finally {
// Close the stream.
in.close();
}
}

关于java - 用这种方法创建新的 .ser 文件有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48858370/

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