我正在创建一个可能很长的对象日志,不想在写入文件之前将它们全部保存在内存中,所以我无法将对象的序列化集合写入文件。我正试图找出在日志记录完成后读取整个对象流的最佳方式。
我注意到以下内容不起作用:
FileInputStream fis = new FileInputStream(log);
ObjectInputStream in = new ObjectInputStream(fis);
while ((obj = in.readObject()) != null) {
// do stuff with obj
}
因为流在到达文件末尾时抛出异常,而不是返回null(可能是因为可以向对象流写入/读取null,导致上面的循环无法正常运行)。
有没有比以下更好的方法来完成我想用上面的循环完成的事情:
FileInputStream fis = new FileInputStream(log);
ObjectInputStream in = new ObjectInputStream(fis);
try {
while (true) {
obj = in.readObject();
// do stuff with obj
}
} catch (EOFException e) {
}
这似乎有点笨拙。对于文件结束对象解决方案,以下是最佳方法吗?
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);
}
}