2015-08-08 44 views
0

我有一個Object數組的對象數組。我想將它轉換爲一個字節數組,然後將其作爲Object數組的數組接收回來。我曾與ByteArrayOutputStream配合使用ObjectOutputStream將其轉換爲字節數組:對象數組的字節數組

ByteArrayOutputStream b = new BAOS(); 
ObjectOutputStream o = new OOS(); 
o.writeObject(obj) // obj being the array 

然後,當我試着去閱讀它,所有我得到的是隻有第一陣列的內容。接收到的對象數組的大小也等於單個數組的大小。

我曾嘗試使用writeObject()迭代,但無濟於事。

好了,所以進一步我試圖多維陣列的方法,以及:

byte[] firstArr = new byte[1]; 
oos.writeObject(orgArr[0]); 
firstArr = baos.toByteArray(); 
byte[] secondArr = new byte[1]; 
oos.writeObject(orgArr[1]); 
secondArr = baos.toByteArray(); 
byte[] combined = new byte[2]; 
combined[0] = firstArr[0]; 
combined[1] = secondArr[1]; 

兩個陣列是相同的,相同的長度和兩個firstArrsecondArr是對象陣列。所以,我有問題是,當我使用反序列化:

ObjectInputStream ois = new ObjectInputStream(
        new ByteArrayInputStream(om.nakedPayload)); 
Object[] list = (Object[]) ois.readObject(); 

陣列列表的長度返回是38.哪個的任2門陣列(firstArr/secondArr)的長度。此外,它包含的數據只是firstArrom.nakedPayload是我從卡夫卡主題中讀取的數據。我們在這裏寫了一個包裝器,它基本上是爲了讀寫目的而預計的一個byte[]

+0

如果只顯示幾行代碼,很難說出錯誤是什麼。 –

+0

瞭解,使用「序列化」是非常複雜的東西(並且有點buggy除外)。不是因爲心靈的隱隱。 –

回答

1

讓我們簡化了任務,並假設你的目標是整數,那麼序列化/反序列化的代碼看起來像以下:

import java.io.*; 

public class ArrayOfArrays { 

    public static void main(String[] args) throws Exception{ 
     String fileName = "myobject.data"; 
     FileOutputStream fileOut = new FileOutputStream(fileName); 
     ObjectOutputStream out = new ObjectOutputStream(fileOut); 

     Integer[][] intArray = new Integer[3][3]; 
     intArray[0] = new Integer[] {11, 12, 13}; 
     intArray[1] = new Integer[] {21, 22, 23}; 
     intArray[2] = new Integer[] {31, 32, 33}; 

     out.writeObject(intArray); 

     FileInputStream fileIn = new FileInputStream(fileName); 
     ObjectInputStream in = new ObjectInputStream(fileIn); 

     Integer[][] intArrayIn = (Integer[][]) in.readObject(); 
    } 
} 


這將給予同樣的「數組的數組」對象回來。下一步,我們可以用任何實現標記接口java.io.Serializable的類來替換Integer。

所有非瞬態字段都將參與序列化/反序列化並與root「array of array」對象一起恢復。

+0

嗯,我也嘗試過這種方法。 – Sagar