ObjectInputStream being initialised causes an EOFException of the type IOException

I have been writing a to-do list app in java and each todo item is stored as an object of the class ToDo (which I created).
The ToDo class is serializable and I am using an ObjectOutputStream to write the objects to a text file. I close the ObjectOutputStream after doing this.
I should probably mention that currently my text file is empty as there are no todos in it and GUI.items is a static ArrayList in my GUI class.

When I run the method that reads the files, an IO exception is thrown on the line:

ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

Here is the method that reads the files:

public void read() {
    try (FileInputStream fileInputStream = new FileInputStream("todo.txt")) {

        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

        GUI.items.clear();

        while (objectInputStream.readObject() != null) {
            GUI.items.add((ToDo) objectInputStream.readObject());
        }

        GUI.updateInterface();

        objectInputStream.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        //JOptionPane.showMessageDialog(null, "Error: To-Do List not found.\nPlease contact the developer.", "Error", JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "Error: To-Do List could not be opened.\nPlease contact the developer.", "Error", JOptionPane.ERROR_MESSAGE);
    } catch (ClassNotFoundException e) {
        JOptionPane.showMessageDialog(null, "Error: To-Do List object type could not be found.\nPlease contact the developer.", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

Why is this exception being thrown and how can I fix it? Thanks.

Jon Skeet
people
quotationmark

Yes, this is behaving as documented:

Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified.

...

Throws:
IOException - if an I/O error occurs while reading stream header

If your file is empty, it doesn't contain the stream header. A file which has been created using an ObjectOutputStream which has been closed after writing 0 objects is not the same thing as an empty file.

people

See more on this question at Stackoverflow