简体   繁体   中英

number of serialized objects in file

I have a class Shape that implements Serializable interface, I saved 3 objects to a file called file.ser and I could successfully retrieve them like following

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.ser"));
Shape[] shapes = new Shape[6];
shapes[0] = (Shape) ois.readObject();
shapes[1] = (Shape) ois.readObject();
shapes[2] = (Shape) ois.readObject();
ois.close();

in this example I know number of objects but in other applications I wouldn't know so I continue reading till getting exception

List<Shape> shapes = new ArrayList<>();
ObjectInputStream ois = null;
try {
    ois = new ObjectInputStream(new FileInputStream("file.ser"));
    while (true) {
        Shape shape = (Shape) ois.readObject();
        shapes.add(shape);
    }
} finally {
    if (ois != null)
        ois.close();
}

is there a better way or this is the only one available?

A better way would be to write the number of contained objects into the file. So when reading you first retrieve the count. Then you know how many objects to read and you can also dimension the array accordingly.

As an alternative you could also write an array or a list of Shapes instead of count + single objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM