2

我正在编写一个类来跟踪比赛中的比赛数据。我想将这个类存储到一个文件中,所以我使用ObjectInputStream. 我正在编写的类实现了可序列化。我得到了一个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)

I'm not sure why this is happening. How do I handle this?

4

2 回答 2

5

You should close ObjectOutputStream, try

 ObjectOutput output = new ObjectOutputStream(bufferOut);
 output.writeObject(this);
 output.close();
于 2013-03-02T05:46:31.983 回答
4

You need to close your output stream, and you also nee to call readObject() not read.

于 2013-03-02T05:47:27.653 回答