[英]Java Serialisation : reading and writing to a file
I have a class called item
which has a few Strings like price, stock etc. 我有一类叫做
item
的类,其中有一些字符串,例如价格,股票等。
I write these to a file as such: 我将这些写入文件:
item[] data = new item[numberofitems];
The array is then filled then: 然后填充数组:
ObjectOutputStream outinv = new ObjectOutputStream(outinvstream);
outinv.writeInt(numberofitems);
for (int i = 0; i < numberofitems; i++)
{
outinv.writeObject(data[i]);
}
This all works fine. 这一切都很好。 The trouble comes when I try reading it in:
当我尝试阅读时会遇到麻烦:
FileInputStream fin = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fin);
inventory = (item[]) ois.readObject();
where f is the file (it definitely finds it) and inventory is an item[]
. f是文件(肯定可以找到它),清单是
item[]
。 However I get a OptionalDataException
但是我得到了
OptionalDataException
Any hints are appreciated! 任何提示表示赞赏!
您必须按照与编写顺序相同的顺序进行读取。首先要写入数组大小,因此需要先读取int,然后再读取Objects。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.