java - Deserializing multiple objects from file without using while(true) -
i have block of code, deserializes multiple objects file. how can avoid using while(true)?
objectinputstream in = new objectinputstream(new fileinputstream( filename)); while (true) { try { myobject o = (myobject) in.readobject(); // object } catch (eofexception e) { break; } } in.close();
you should write either collection (with size), or put marker before each object:
try { (;in.readboolean();) { myobject o = (myobject) in.readobject(); } } catch (eofexception e) { // ... }
when write object, write boolean before (it take 1 byte if remember part):
for (myobject o : iterable) { out.writeboolean(true); out.writeobject(o); } out.writeboolean(false);
if iterable
collection or map, can use default serialization:
out.writeobject(iterable); // default collection serialization
beside, don't catch exception each item, catch globally (especially eofexception!): better performance reasons.
i don't know if work java 7, code + loop can written this:
try (objectinputstream in = new objectinputstream(new fileinputstream( filename))) { (;in.readboolean();) { myobject o = (myobject) in.readobject(); } } catch (eofexception e) { // ... } // no need close, try-with-resources job you.
Comments
Post a Comment