javanetbeansdeserializationobjectinputstreameofexception

EOFException with ObjectInputStream


I have read other questions similar to this but didn't help much. So I have some serialized content in a file and I am trying to read it and print it on the console, content is getting printed fine but at the end, it's showing an EOFException. Is there any way to fix my code to avoid this exception?

try {
            File file = new File("EnrolledStudentsSerial.txt");
 
            FileInputStream fi = new FileInputStream(file);
            ObjectInputStream input = new ObjectInputStream(fi);
            while(true) {
                System.out.println(input.readObject());
            }
        } 
        catch (IOException | ClassNotFoundException e) {
            System.out.println("Error: " + e); 
        }

Solution

  • I don't think you want to 'avoid' this exception.

    You need to know when you come to the end of the input, and the EOFException is what is telling you you've come to the end of the input.

    Rather, you want to stop treating it as an error condition, since it is not an error, it is normal and expected.

    try {
       … code as before … 
    } 
    catch (EOFException e) {
       // end of input, nothing to do here
    }
    catch (IOException | ClassNotFoundException e) {
        System.out.println("Error: " + e); 
    }