在Java中从文件中完全读取对象流的最佳方法是什么? [英] What is the best way to fully read a stream of objects from a file in Java?

查看:194
本文介绍了在Java中从文件中完全读取对象流的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个可能很长的对象日志,并且不希望在写入文件之前将它们全部保存在内存中,因此我无法将对象的序列化集合写入文件。在完成日志记录后,我正试图找出整个对象流中的最佳阅读方式。

I'm creating a potentially long log of objects and do not want to keep them all in memory before writing to a file, so I can't write a serialized collection of the objects to a file. I'm trying to find out the 'best' way of reading in the entire stream of objects after logging has been finished.

我注意到以下内容不起作用:

I have noticed that the following does not work:

FileInputStream fis = new FileInputStream(log);
ObjectInputStream in = new ObjectInputStream(fis);
while ((obj = in.readObject()) != null) {
  // do stuff with obj
}

因为流在到达文件末尾时抛出异常而不是返回null(可能是因为可以向对象流写入/读取null,导致上面的循环没有表现得像预期的那样)。

because the stream throws an exception when it reaches the end of a file rather than returning null (presumably because one can write/read null to object streams, causing the above loop not to behave as expected).

有没有更好的方法来完成我想用上述循环完成的事情:

Is there a better way to do something like what I want to accomplish with the above loop than:

FileInputStream fis = new FileInputStream(log);
ObjectInputStream in = new ObjectInputStream(fis);
try {
  while (true) {
    obj = in.readObject();
    // do stuff with obj
  }
} catch (EOFException e) {
}

这看起来有点笨拙。对于文件结束对象解决方案,以下是最好的方法吗?

This seems a little clumsy. For an end-of-file object solution, is the following the best way?

private static final class EOFObject implements Serializable {
  private static final long serialVersionUID = 1L;
}

void foo() {
  Object obj;
  while (!((obj = in.readObject()) instanceof EOFObject)) {
    BidRequest bidRequest = ((BidRequestWrapper) obj).getBidRequest();
    bidRequestList.add(bidRequest);
  }
}


推荐答案

您的解决方案似乎很好只需确保你有一个 finally 子句,你可以关闭你的流。

Your solution seems fine. Just make sure you have a finally clause, where you close your stream.

或者,你可以创建一个EOF你的对象,并在最后添加它。因此,您可以检查当前读取的对象是否为 EofObject ,以及 break

Alternatively, you can create an EOF object of yours, and add it at the end. Thus you can check if the currently read object is the EofObject, and break at that point.

这篇关于在Java中从文件中完全读取对象流的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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