Reputation: 616
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();
}
Upvotes: 0
Views: 1005
Reputation: 4835
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.
Upvotes: 2