Search code examples
javaserializationfileinputstreamobjectinputstream

Issue with Deserialization


I have a method in my program that reads from a file, and I have associated with both a FileInputStream variable and an ObjectInputStream variable. However, I do not know how many objects will be serialized in the file when I run the program, so I do not know how many objects to deserialize using the method readObject(). This is the method from my project:

public void importResults(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
    TestEntry entry = null;
    try(FileInputStream fis = new FileInputStream(file)) {
        ObjectInputStream ois = new ObjectInputStream(fis);

        tests.clear();

        entry = (TestEntry)ois.readObject();

        tests.add(entry);

        ois.close();
    }
}

The variable entry is where I will store TestEntry objects that I deserialize from the file. The problem is, if I try to deserialize too many objects, I get an EOFException. How do I get my program to figure out how many objects there are serialized in the file so I can deserialized the right amount? Any help will be greatly appreciated! Thank you.


Solution

  • Just read in a loop until you get EOFException, which is thrown when there are no more objects to read.