Java将对象输入流读取到数组列表中?
下面的方法应该将二进制文件读入arrayList
。但是得到一个 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 循环。有什么想法吗?
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();
}
}
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据其他答案,您正在循环中阅读两次。您的另一个问题是空测试。
readObject()
仅在您写入 null 时返回 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 areadObject()
loop is问题是您在循环中调用 readObject() 两次。试试这个:
The problem is that you are calling readObject() twice in the loop. Try this instead:
您正在 while 测试中读取一个对象:
然后您正在读取以下对象:
因此,在一次迭代中您应该只读取一个对象
You're reading an object in the while test:
Then you're reading the next object in:
So in one iteration you should read only one object
你可以试试这个。祝你好运!
You can try this. Good luck!