0

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() )
        System.out.println(s);
}catch (IOException | ClassNotFoundException e){
    e.printStackTrace();
}
T4l0n
  • 595
  • 1
  • 8
  • 25
  • Once you have read all the objects, stop reading from the ObjectInputStream. If you don't know how many objects there are, write the count to the ObjectOutputStream before writing the objects to it. Even easier, if you don't have a huge number of objects, is to write an array. (Don't write a List; reading the List would require an unsafe cast.) – VGR Feb 08 '16 at 20:00
  • Are you creating `file.bin`? If so, how are you doing that? – Ryan Jackman Feb 08 '16 at 20:03
  • @VGR Reading *anything* from an object stream requires an unsafe cast. Pretending a count isn't always practical, and it is also pointless given that `EOFException` already exists. – user207421 Feb 07 '17 at 16:57
  • @Fishstick If he wasn't creating it how could he get an `EOFException` reading from it? – user207421 Feb 07 '17 at 16:57

1 Answers1

2

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();
        System.out.println(s);
    }
} 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.

TimK
  • 4,635
  • 2
  • 27
  • 27