使用ObjectInputStream读取文件时出现EOFException [英] EOFException when reading files with ObjectInputStream

查看:302
本文介绍了使用ObjectInputStream读取文件时出现EOFException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上遇到了类似的问题:阅读objectinputstream时Java中的EOFexception ,但我找不到一个干净的代码的答案。

I basically have a similar problem as stated here: EOFexception in Java when reading objectinputstream, but I don't find an answer with clean code.

答案指出 ObjectInputStream#readObject 将在读者到达时抛出异常文件的结尾。在网上寻找解决方案之后,我还没有找到解决方案。对于这种情况可能是一个好的和干净的解决方案吗?

The answer states that the ObjectInputStream#readObject will throw the exception when the reader reachs the End Of File. After looking in the web for a solution, I haven't found a solution. Could be a good and clean solution for this case?

注意:我已经尝试过这个(但它看起来很难看并且不是干净的代码)。我正在寻找更好的解决方案:

Note: I have tried this (but it looks ugly and is not clean code). I'm looking for a better solution:

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时才会停止通过 writeObject(),如果没有,你将获得 EOFException

That's what's supposed to happen. Your code is wrong. Check the Javadoc. readObject() only returns null if you wrote a null. It doesn't say anything about returning a null at EOF. Looping until readObject() returns null will only stop if you ever wrote a null via writeObject(), and if you didn't you will get an EOFException.

这篇关于使用ObjectInputStream读取文件时出现EOFException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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