gpt4 book ai didi

java - 读取二进制文件异常

转载 作者:行者123 更新时间:2023-12-01 18:48:41 25 4
gpt4 key购买 nike

我收到此异常。是因为我没有捕获他们吗?

 java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2577)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at ReadStudentRecord.readRecord(ReadStudentRecord.java:34)
at ReadStudentRecordTest.main(ReadStudentRecordTest.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

这是我读取二进制文件的类:

 import java.io.*;


public class ReadStudentRecord {

private ObjectInputStream input;

public void openFile() {

try {
input = new ObjectInputStream(new FileInputStream("student.dat"));

} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} // end of open file method

public void readRecord() {

Q4 student;

System.out.println("Student Name\t\t Student average Mark");
try {

while (true) {


student = (Q4) input.readObject();

System.out.println(student.getStudentName() + "\t\t\t" + student.averageMark(student.getMark()));

}
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}

}// end of readRecord method

public void closeFile() {
try // close file and exit
{
if (input != null)
input.close();
System.exit(0);
} // end try
catch (IOException ioException) {
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end method closeFile
} // end of class

它工作得很好,除了我得到了上面的异常,我不知道可能是什么原因造成的。我就是不知道我做错了什么。

最佳答案

您正在无限循环中从文件中读取对象。

while (true) {
student = (Q4) input.readObject();
...
}

最终流到达文件末尾,但您仍然要求更多对象,这就是抛出异常的原因。

<小时/>

一个可能的解决方案是捕获 EOFException,这意味着不再存在任何对象。

try {
while (true) {
student = (Q4) input.readObject();
...
}
}
catch (EOFException eof) {
// Reached end of file. Do anything here, if you want.
// Or else, just ignore the end of file, and proceed out of the block.
}
finally {
// Some other stuff.
// Do not forget to close the stream.
input.close();
}

关于java - 读取二进制文件异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16624360/

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