serialization - What is the best way to fully read a stream of objects from a file in Java? -
i'm creating potentially long log of objects , not want keep them in memory before writing file, can't write serialized collection of objects file. i'm trying find out 'best' way of reading in entire stream of objects after logging has been finished.
i have noticed following not work:
fileinputstream fis = new fileinputstream(log); objectinputstream in = new objectinputstream(fis); while ((obj = in.readobject()) != null) { // stuff obj }
because stream throws exception when reaches end of file rather returning null (presumably because 1 can write/read null object streams, causing above loop not behave expected).
is there better way want accomplish above loop than:
fileinputstream fis = new fileinputstream(log); objectinputstream in = new objectinputstream(fis); try { while (true) { obj = in.readobject(); // stuff obj } } catch (eofexception e) { }
this seems little clumsy. end-of-file object solution, following 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. make sure have finally
clause, close stream.
alternatively, can create eof object of yours, , add @ end. can check if read object eofobject
, , break
@ point.
Comments
Post a Comment