Deserialize multiple Java Objects

前端 未结 3 430
感动是毒
感动是毒 2020-12-10 15:59

hello dear colleagues,

I have a Garden class in which I serialize and deserialize multiple Plant class objects. The serializing is working but the deserializing is n

3条回答
  •  粉色の甜心
    2020-12-10 16:14

    It may not always be feasible to deserialize a whole list of objects (e.g., due to memory issues). In that case try:

        ObjectInputStream in = new ObjectInputStream(new FileInputStream(
                filename));
    
        while (true) {
            try {
                MyObject o = (MyObject) in.readObject();
                // Do something with the object
            } catch (EOFException e) {
                break;
            }
        }
    
        in.close();
    

    Or using the Java SE 7 try-with-resources statement:

        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(
                filename))) {
            while (true) {
                MyObject o = (MyObject) in.readObject();
                // Do something with the object
            }
        } catch (EOFException e) {
            return;
        }
    

提交回复
热议问题