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
}
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);
}
}
Your solution seems fine. Just make sure you have a
finallyclause, where you close your stream.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, andbreakat that point.