Java读取对象输入流到arraylist? [英] Java read object input stream into arraylist?
问题描述
下面的方法应该将二进制文件读入 arrayList
。但是在java.io.ObjectInputStream中获得 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)
main的第23行调用方法,第400行是下面的while循环。任何想法?
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根据其他答案,你在循环中阅读两次。你的另一个问题是空测试。 readObject()
只有在写入空值时才返回null,而不是在EOS,因此将它用作循环终止测试没有多大意义。正确终止 readObject()
循环是
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;
}
这篇关于Java读取对象输入流到arraylist?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!