2013-05-01 136 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