2015-08-08 41 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