Java中读取objectinputstream时出现EOF异常

发布于 2024-08-22 13:28:58 字数 366 浏览 5 评论 0原文

我想读取输出到 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰火雁神 2024-08-29 13:28:58

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

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

注意“o”的初始化是多余的。

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

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文