我有序列化对象的功能并将其存储在二进制文件中,还有另一个对象只是为了计算到目前为止我在文件中存储了多少个对象,所以 我可以稍后使用该计数器来浏览文件并反序列化并读取它。 这是我的写功能:
// Read Counter file to know how many stored objects to go through them
Maintenance check = new Maintenance();
FileInputStream inStream = new FileInputStream("Counter.dat");
ObjectInputStream objectInput = new ObjectInputStream(inStream);
check = (Maintenance) objectInput.readObject();
int Counter1 = check.getObjectsNumber(); // function I created in the Maintenance class to return number of object stored
inStream.close();
// Read the stored objects
//here is my problem begin
FileInputStream inStream2 = new FileInputStream("MainStore.dat");
ObjectInputStream objectInputFile = new ObjectInputStream(inStream2);
// Create array of objects
Class1[] arrayOfObjects = new Class1[Counter1];
// Read the serialized objects from the file.
for (int i = 0; i < Counter1; i++) {
arrayOfObjects[i] = (Class1) objectInputFile.readObject(); // here is the error pointed by compiler
}
objectInputFile.close();
for (int i = 0; i < 2; i++) {
// here I should have array of all objects ready to read details
}
上一个函数工作正常,下一步是读取文件中的对象读取的函数,我使用Counter.dat查看MainStore.dat上存储的对象数,它给出了正确的数字。 这是读函数:
Caused by: java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at registerController.CheckPlaceAvailabilityAction(registerController.java:120)
... 58 more
一切看起来都很好,除了最后一点&#34; //从&#34;中读取序列化对象。它给了我这个错误
BasicDBObject updateFields = new BasicDBObject("pogId", supcInfo.getPogId()).append("mrp", supcInfo.getMrp()); // Rest of fields.
BasicDBObject dbObject = new BasicDBObject("$set",updateFields);
当我仅仅读取一个对象进行测试时,它完美无缺,并为我返回第一个存储对象,当我尝试读取所有存储的对象时发生错误。
答案 0 :(得分:1)
显然,你不能像你一样透明地连接/追加ObjectOutputStreams
。
请参阅the docs:
[]构造函数将序列化流标头写入 基础流
因此,新流将首先写入一些标头,这需要一个新的输入流来读取。否则,输入流将尝试将标头读取为序列化对象,并且将失败,因为这些标头不是有效的序列化对象数据。