gpt4 book ai didi

Java序列化: reading and writing to a file

转载 作者:行者123 更新时间:2023-11-30 03:12:50 25 4
gpt4 key购买 nike

我有一个名为 item 的类,其中包含一些字符串,例如价格、库存等。

我将这些写入文件,如下所示:

item[] data = new item[numberofitems]; 

然后填充数组:

ObjectOutputStream outinv = new ObjectOutputStream(outinvstream);

outinv.writeInt(numberofitems);

for (int i = 0; i < numberofitems; i++)
{

outinv.writeObject(data[i]);
}

这一切都运行良好。当我尝试将其读入以下内容时,麻烦就来了:

FileInputStream fin = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fin);
inventory = (item[]) ois.readObject();

其中 f 是文件(它肯定会找到它),而 inventory 是一个 item[]。但是我得到了 OptionalDataException

如有任何提示,我们将不胜感激!

最佳答案

您必须按照与写入相同的顺序读取。您首先写入数组大小,因此您需要先读取 int,然后再读取对象

关于Java序列化: reading and writing to a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33265010/

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