ObjectInputStream抛出EOFException

时间:2013-03-02 05:40:51

标签: java file file-io filereader serializable

我正在写一堂课来跟踪比赛中的比赛数据。我想将此类存储到文件中,因此使用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)

我不确定为什么会这样。我该如何处理?

2 个答案:

答案 0 :(得分:5)

你应该关闭ObjectOutputStream,试试

 ObjectOutput output = new ObjectOutputStream(bufferOut);
 output.writeObject(this);
 output.close();

答案 1 :(得分:3)

您需要关闭输出流,并且还需要调用readObject()而不是读取。