我正在写一个类来跟踪比赛中的比赛数据。我想将此类存储到文件中,因此正在使用ObjectInputStream
。我正在编写的类实现了Serializable。我得到一个EOFException
,在SO和其他地方找不到的任何解决方案都不能真正解决此问题。
我的文件编写器是:
public void writeToFile(String path) {
File f = new File(path);
if(f.exists()) f.delete();
try {
OutputStream fileOut = new FileOutputStream(path);
OutputStream bufferOut = new BufferedOutputStream(fileOut);
ObjectOutput output = new ObjectOutputStream(bufferOut);
output.writeObject(this);
} catch(IOException e) {}
}
我的文件阅读器是:
public static DivisionDataFTC readFromFile(String path) {
try {
InputStream fileIn = new FileInputStream(path);
InputStream bufferIn = new BufferedInputStream(fileIn);
ObjectInput input = new ObjectInputStream(bufferIn);
System.out.println(input.read());
} catch(Exception e) {
System.out.println(path);
e.printStackTrace();
}
if(1==1) throw new Error("Could not read DivisionDataFTC at " + path);
return null;
}
我已成功写入数据-我已验证文件不为空。 (如果相关,其内容始终为7.99kb)。
需要明确的是,在ObjectOutputStream的实例化上不会发生该错误。这就是使这个问题与众不同的原因-错误发生在readObject()调用上。我的输出是非常长的
EOFException
:java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2571)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at java.util.ArrayList.readObject(ArrayList.java:733)
(...cut out most of this because nobody wants to read it...)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at tournamentftc.DivisionDataFTC.readFromFile(DivisionDataFTC.java:297)
at firstscouting.FIRSTScouting.runGUI(FIRSTScouting.java:82)
at firstscouting.FIRSTScouting.main(FIRSTScouting.java:101)
Exception in thread "main" java.lang.Error: Could not read DivisionDataFTC at C:\Users\Noah\Desktop\out.ser
at tournamentftc.DivisionDataFTC.readFromFile(DivisionDataFTC.java:303)
at firstscouting.FIRSTScouting.runGUI(FIRSTScouting.java:82)
at firstscouting.FIRSTScouting.main(FIRSTScouting.java:101)
我不确定为什么会这样。我该如何处理?
最佳答案
您应该关闭ObjectOutputStream,尝试
ObjectOutput output = new ObjectOutputStream(bufferOut);
output.writeObject(this);
output.close();
关于java - ObjectInputStream引发EOFException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15171184/