Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java read object input stream into arraylist?

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();
    }
}
like image 546
ash Avatar asked Jun 26 '11 14:06

ash


1 Answers

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;
}
like image 167
user207421 Avatar answered Sep 20 '22 13:09

user207421