I am creating a potentially long log of objects and do not want to store them all in memory before writing to a file, so I cannot write a serialized collection of objects to a file. I am trying to figure out the "best" way to read the entire stream of objects after registration is complete.
I 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 the file rather than returning zero (presumably because you can write / read zero streams of objects, as a result of which the above loop will not behave as expected).
Is there a better way to do something like what I want to accomplish using 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) {
}
. ?
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);
}
}