0
我有序列化對象並將其存儲在二進制文件中的功能,也是另一個對象,用於統計目前爲止我已存儲在文件中的對象數量,因此我可以使用計數器稍後再通過該文件並反序列化並閱讀它。 這是我寫的功能:從java中的二進制文件中讀取對象
Class2 dad = new Class2(DadName.getText(), DadLastName.getText());
Class1 son = new Class1(FirstName.getText(), dad, "Session");
// Write object to file
FileOutputStream outStream = new FileOutputStream(new File("MainStore.dat"), true);
ObjectOutputStream objectOutputFile = new ObjectOutputStream(outStream);
objectOutputFile.writeObject(son);
objectOutputFile.close();
// Update the objectcounter file by
// Maintenance is a class I use just to save object contain information about number of files,increase them, decrease them.
Maintenance check = new Maintenance();
FileInputStream inStream = new FileInputStream("Counter.dat");
ObjectInputStream objectInput = new ObjectInputStream(inStream);
check = (Maintenance) objectInput.readObject();
inStream.close();
check.increaseObject();
FileOutputStream outStream1 = new FileOutputStream("Counter.dat");
ObjectOutputStream objectOutputFile1 = new ObjectOutputStream(outStream1);
objectOutputFile1.writeObject(check);
objectOutputFile1.close();
先前的功能工作得很好,下一步就是函數讀取讀取的對象從文件回來,我用Counter.dat看到存儲在MainStore對象的數量。 dat,它給了我正確的編號。 這裏是讀功能:
// 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
}
一切都看起來不錯,除了最後一位「//讀取從序列化對象」。它給了我這個錯誤
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
,當我只有讀一個對象來測試它,它的工作完美,並返回第一個存儲的對象對我來說,錯誤發生了,當我嘗試讀取所有存儲的對象。
如果可以,您可能需要發佈MVCE(http://stackoverflow.com/help/mcve)。 –
你爲什麼要堅持櫃檯?你確定你的文件在測試過程中沒有被損壞嗎?我建議刪除它並重新開始一個新文件。 – JimmyB