The method below is supposed to read a binary file into an arrayList
. But getting a java.io.EOFException
:
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2553) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1296) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350) at .... Read(Tester.java:400) at .... main(Tester.java:23)
Line 23 at main just calls the method, line 400 is the while loop below. Any ideas?
private static void Read() {
try {
ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("/file.bin"));
while (objIn.readObject() != null) {
list.add((Libreria) objIn.readObject());
}
objIn.close();
} catch(Exception e) {
e.printStackTrace();
}
}
As per the other answers you are reading twice in the loop. Your other problem is the null test. readObject()
only returns null if you have written a null, not at EOS, so there's not much point in using it as a loop termination test. The correct termination of a readObject()
loop is
catch (EOFException exc)
{
in.close();
break;
}