簡體   English   中英

從Java中的二進制文件讀取對象

[英]Read objects from binary files in 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

當我僅讀取一個對象進行測試時,它可以完美工作並為我返回第一個存儲的對象,當我嘗試讀取所有存儲的對象時發生了錯誤。

顯然,您不能像您那樣透明地串聯/附加ObjectOutputStreams

文檔

[The]構造函數將序列化流標頭寫入基礎流

因此,新的流將首先寫入一些標頭,這將需要新的輸入流來讀取。 否則,輸入流將嘗試將標頭讀取為序列化對象,並且將失敗,因為這些標頭不是有效的序列化對象數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM