EOFException when reading files with ObjectInputStream [duplicate]

Solution 1:

That's what's supposed to happen. Your code is wrong. Check the Javadoc. readObject() only returns null if you wrote a null. It doesn't say anything about returning a null at EOF. Looping until readObject() returns null will only stop if you ever wrote a null via writeObject(), and if you didn't you will get an EOFException.

Solution 2:

@EJP's answer has nailed it.

However if you are a paid-up member of the "exceptions should't be used for normal flow control" club* then you can avoid having to catch the exception if you can use some other means to determine when to stop; for example

  • You could start the stream with a count sent as an int or an Integer object.
  • You could mark the end the stream by sending a null.
  • You could mark the end the stream by sending a special object that means "this is the end". It does not need to be a MyClass instance.
  • You could send a List<MyClass> ... though that means that you can't "stream" the objects.

Note that this implies that you are able to change the sender-side code ...


* Membership of this club requires either the ability to assimilate circular arguments, or willingness to blindly accept dogma as truth. :-)


Rather than repeat the arguments ad nauseam, here are some links to some of my answers related to the "normal flow control" debate:

  • Cost of compound if/or versus try/catch in Java 6
  • What is an alternative to exceptions for flow control?
  • Regex or Exception Handling?
  • Check if a file exists before calling openFileInput
  • Which is faster, try catch or if-else in java (WRT performance)

If you read through them, you will see that I don't come down firmly on either side of the fence. Rather, my view is that you should understand the trade-offs, and make a decision about whether exceptions are appropriate or not on a case-by-case basis.

Solution 3:

You could try this:

boolean check=true;
while (check) {
   try{
       System.out.println(ois.readObject());
   } catch(EOFException ex){
       check=false;
   }
}

Solution 4:

I encountered this error because I had forgot to close an ObjectOutputStream in the code that wrote the data. Once I wrote the data again with code that closed the output stream the data was able to be read in fine.