Java中读取objectinputstream时出现EOF异常
我想读取输出到 .dat 文件的多个对象(我自己的类 Term),但我总是得到 nullPointException 或 EOFException。
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(masterFile));
Object o = null;
while(( o = inputStream.readObject()) != null){
Term t = (Term)o;
System.out.println("I found a term");
}
I want to read multiple objects (my own class Term) that I have output to a .dat file, but I always get a nullPointException or EOFException.
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(masterFile));
Object o = null;
while(( o = inputStream.readObject()) != null){
Term t = (Term)o;
System.out.println("I found a term");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅 Javadoc。
readObject()
在 EOF 处不返回 null。它会抛出 EOFException。 它返回 null 的唯一方法是在另一端写入 null,而这不一定是终止读取循环的好理由。简而言之,您的代码是错误的。
注意“o”的初始化是多余的。
注意 (2) 您发布的代码不能抛出
NullPointerException,
,除非masterFile
为 null。这是一份严肃的报告还是只是一个猜测?See the Javadoc.
readObject()
doesn't return null at EOF. It throwsEOFException.
The only way it can return a null is if you wrote a null at the other end, and that's not necessarily a good reason for terminating the read loop.In short your code is wrong.
NB the initialization of 'o' is redundant.
NB (2) The code you posted cannot throw
NullPointerException,
unlessmasterFile
is null. Is that a serious report or just a guess?