Home Ask Login Register

Developers Planet

Your answer is one click away!

T4l0n February 2016

EOFException from reading a file

The output is correct but it's followed by an EOFException. I read the documentation but still i don't know how to solve this

try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.bin"))){
    for(Ser s = (Ser)ois.readObject(); s!=null; s=(Ser)ois.readObject() )
}catch (IOException | ClassNotFoundException e){


TimK February 2016

You are assuming that readObject returns null if there is no data, but in fact it throws EOFException. The simplest fix is just to catch the exception:

try(...) {
    for(;;) {
        Ser s = (Ser)ois.readObject();
} catch(EOFException e) {
    // normal loop termination
} catch(IOException | ClassNotFoundException e){
    // error

Be aware that some people and coding standards consider it bad practice to have an exception thrown in non-error conditions, like reaching the end of input in this case.

Post Status

Asked in February 2016
Viewed 3,113 times
Voted 8
Answered 1 times


Leave an answer

Quote of the day: live life