4

我基本上有一个与此处所述类似的问题:EOFexception in Java when reading objectinputstream,但我没有找到干净代码的答案。

答案表明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();
4

5 回答 5

13

这就是应该发生的事情。你的代码是错误的。检查Javadoc。readObject()null当您编写了null. 它没有说明在 EOF 处返回空值。只有当你写过via时,循环直到readObject()返回null才会停止,如果你没有写过,你会得到一个.nullwriteObject()EOFException

于 2012-10-02T03:27:34.363 回答
12

@EJP 的回答已经确定了。

但是,如果您是“异常不应用于正常流量控制”俱乐部的付费会员*,那么如果您可以使用其他方式确定何时停止,则可以避免捕获异常;例如

  • int您可以使用作为对象或对象发送的计数来启动流Integer
  • 您可以通过发送一个null.
  • 您可以通过发送一个表示“这是结束”的特殊对象来标记流的结束。它不需要是一个MyClass实例。
  • 您可以发送List<MyClass>... 虽然这意味着您不能“流式传输”对象。

请注意,这意味着您可以更改发送方代码...


* 该俱乐部的会员要求要么有能力吸收循环论证,要么愿意盲目地接受教条作为真理。:-)


与其重复那些令人作呕的论点,这里有一些链接指向我与“正常流量控制”辩论相关的一些答案:

如果你通读它们,你会发现我并没有坚定地站在栅栏的任何一边。相反,我的观点是你应该了解权衡,并根据具体情况决定例外是否合适。

于 2012-10-02T03:50:33.873 回答
4

你可以试试这个:

boolean check=true;
while (check) {
   try{
       System.out.println(ois.readObject());
   } catch(EOFException ex){
       check=false;
   }
}
于 2015-01-22T04:23:54.990 回答
1

I encountered this error because I had forgot to close an ObjectOutputStream in the code that wrote the data. Once I wrote the data again with code that closed the output stream the data was able to be read in fine.

于 2020-02-14T22:32:36.813 回答
-1

虽然到达文件末尾时readObject()不会返回,但如果您从一开始就控制文件,您总是可以在关闭输出流之前添加。它将作为对象传递,但您可以像这样测试文件结尾:NULLNULL

Boolean complete = false;
ObjectInputStream in = <...>

while(complete != true) {
    Object test = (Object)in.readObject();
    if(test != null) { someArrayList.add(test); }
        else { complete = true; }
}
于 2015-05-29T09:46:38.483 回答