Java中的EOFexception在读取objectinputstream时 [英] EOFexception in Java when reading objectinputstream

查看:173
本文介绍了Java中的EOFexception在读取objectinputstream时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取我输出到.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(我找到了一个术语);
}


解决方案

请参阅Javadoc。 readObject()在EOF时不返回null。它抛出 EOFException。它返回null的唯一方法是在另一端写入null,这不一定是终止读循环的好理由。 / p>

简而言之,你的代码是错误的。



注意'o'的初始化是多余的。



注意(2)您发布的代码不能抛出 NullPointerException,除非 masterFile 为空。这是一个严肃的报告还是只是一个猜测?


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");
        }

解决方案

See the Javadoc. readObject() doesn't return null at EOF. It throws EOFException. 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, unless masterFile is null. Is that a serious report or just a guess?

这篇关于Java中的EOFexception在读取objectinputstream时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆