gpt4 book ai didi

java - 文件中序列化对象的数量

转载 作者:行者123 更新时间:2023-11-30 02:58:46 26 4
gpt4 key购买 nike

我有一个类Shape,它实现了Serialized接口(interface),我将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();
}

有更好的方法还是这是唯一可用的方法?

最佳答案

更好的方法是将包含的对象数量写入文件中。因此,在阅读时,您首先检索计数。然后您就知道要读取多少个对象,并且还可以相应地确定数组的大小。

作为替代方案,您也可以编写一个数组或形状列表,而不是 count + 单个对象。

关于java - 文件中序列化对象的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36483371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com