2013-05-01 104 views
0
int[] myIntArray; 
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024); 
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new DeflaterOutputStream(byteArrayOutputStream)); 
objectOutputStream.writeObject(myIntArray); 

现在,ObjectOutputStream取对象并直接对其进行序列化。 DeflaterOutputStream压缩序列化结果,然后压缩结果存储在ByteArrayOutputStream对象反序列化 - 从序列化对象中取回int数组对象

有人可以告诉我如何反序列化并返回我原来的int数组? Plz分享这个编码?

回答

1
objectOutputStream.close(); 
byte[] serialized = byteArrayOutputStream.getBytes(); 

// and then read back using symmetric constructs as when writing, but using 
// input streams instead of output streams: 

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serialized); 
ObjectInputStream objectInputStream = 
    new ObjectInputStream(new InflaterInputStream(byteArrayInputStream)); 
int[] myDesererializedIntArray = (int[]) objectInputStream.readObject(); 
+0

在转换为字节之前,您可能需要关闭或完成流。我会编辑我的答案。 – 2013-05-01 16:06:41

+0

查看我的完整代码在这里http://stackoverflow.com/questions/16321507/java-deserialization-error-invalid-stream-header – 2013-05-01 16:22:52

+0

好的。我终于找到了问题。您必须使用InflaterInputStream而不是DeflaterInputStream。很抱歉没有尽早测试我的解决方案。我现在已经测试成功了。 – 2013-05-01 16:31:40