开发者

Java read object input stream into arraylist?

开发者 https://www.devze.com 2023-03-15 06:45 出处:网络
The method below is supposed to read a binary file into an arrayList. But getting a java.io.EOFException:

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();
    } catc开发者_Python百科h(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;
}


The problem is that you are calling readObject() twice in the loop. Try this instead:

MediaLibrary obj = null;
while ((obj = (MediaLibrary)objIn.readObject()) != null) {
     libraryFromDisk.add(obj);
}


You're reading an object in the while test:

while (objIn.readObject() != null)

Then you're reading the next object in:

libraryFromDisk.add((MediaLibrary) objIn.readObject());

So in one iteration you should read only one object

private static void Load() {
    try {
        ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("/file.bin"));
        Object object = objIn.readObject();
        while (object != null) {
           libraryFromDisk.add((MediaLibrary) object);
           object = objIn.readObject();

        }
        objIn.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
}


You can try this. Good luck!

private static void Load() {
try {
    ObjectInputStream objIn = new ObjectInputStream(new FileInputStream("/file.bin"));
    boolean check=true;
    while (check) {

try{
object = objIn.readObject();
libraryFromDisk.add((MediaLibrary) object);
}catch(EOFException ex){
check=false;
}

    }
    objIn.close();
} catch(Exception e) {
    e.printStackTrace();
}
}
0

精彩评论

暂无评论...
验证码 换一张
取 消