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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -