我基本上有一个类似的问题,如此处所述:Java中读取objectinputstream时出现EOF异常 https://stackoverflow.com/q/2308128/1065197,但我找不到干净代码的答案。
答案指出ObjectInputStream#readObject
当读取器到达文件末尾时将抛出异常。在网上寻找解决方案后,我还没有找到解决方案。对于这种情况,可能是一个好的、干净的解决方案吗?
注意:我已经尝试过这个(但它看起来很丑而且不是干净的代码)。我正在寻找更好的解决方案:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
try {
Object o;
while ((o = ois.readObject()) != null) {
if (o instanceof MyClass) {
MyClass m = (MyClass)o;
//use the object...
}
}
} catch (EOFException eofex) {
//do nothing
} catch (IOException ioex) {
throw ioex;
//I have another try/catch block outside to control the life of the ObjectInputStream
}
//later in the code...
ois.close();
这就是应该发生的事情。你的代码是错误的。检查 Javadoc。readObject()
只返回null
如果你写了一个null
。它没有说任何关于在 EOF 处返回 null 的信息。循环直到readObject()
回报null
只有当你写过时才会停止null
via writeObject()
,如果你不这样做,你会得到一个EOFException
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)