Search code examples
javafilefile-iofilereaderserializable

ObjectInputStream throws EOFException


I'm writing a class to keep track of competition data at a tournament. I want to store this class to a file, so am using an ObjectInputStream. The class I am writing implements Serializable. I'm getting an EOFException, and none of the solutions I've found on SO and elsewhere actually address this issue.

My file writer is:

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) {}
}

My file reader is:

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;
}

I write the data successfully - I have verified that the file is not empty. (Its contents, if relevant, are consistently 7.99kb).

To be clear, the error does not occur on the instantiation of the ObjectOutputStream. This is what makes this question different - the error occurs on the readObject() call. My output is a remarkably long 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?


Solution

  • You should close ObjectOutputStream, try

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