簡體   English   中英

文件中序列化對象的數量

[英]number of serialized objects in file

我有一個實現了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();

在這個例子中,我知道對象的數量,但是在其他應用程序中,我不知道,所以我繼續閱讀直到得到異常

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();
}

有沒有更好的方法,或者這是唯一可用的方法?

更好的方法是將包含的對象數寫入文件中。 因此,在閱讀時,您首先要檢索計數。 然后,您知道要讀取多少個對象,並且還可以相應地調整數組的尺寸。

或者,您也可以編寫一個數組或一個Shape列表,而不是count +單個對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM