简体   繁体   English

文件中序列化对象的数量

[英]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 我有一个实现了Serializable接口的Shape类,我将3个对象保存到一个名为file.ser的文件中,我可以像下面这样成功地检索它们

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. 或者,您也可以编写一个数组或一个Shape列表,而不是count +单个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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