2012-11-12 92 views
1

我想測試一個程序,並且我需要訪問ReadExternal函數,但是我在ObjectInputStream上發生了StreamCorrupted異常。 我知道我需要使用的writeObject寫入的對象,但不知道該怎麼辦呢?當通過ObjectInputStream反序列化時發生StreamCorruptedException

ObjectOutputStream out=new ObjectOutputStream(new ByteArrayOutputStream()); 
    out.writeObject(ss3); 
    ss3.writeExternal(out); 
    try{ 
     ByteInputStream bi=new ByteInputStream(); 
     bi.setBuf(bb); 
     out.write(bb); 
     ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bb)); 
     String s1=(String) in.readObject(); 
     } 
     catch(Exception e){ 
      e.printStackTrace(); 
     } 
+2

你能提供一個簡單的,你自己想要做的自包含的例子嗎?您不應該直接調用read/writeExternal,因爲它們被對象流使用。 –

+0

這是什麼'bb'?正如彼得所說,一個簡短但完整的程序真的會有所幫助。 –

回答

5

顯然,你試圖寫同一個對象兩次到輸出流:

out.writeObject(ss3); 
ss3.writeExternal(out); // <-- Remove this! 

第二次寫入錯誤地使用了writeExternal()方法,該方法不應該明確調用,但將由ObjectOutputStream調用。

而且:out.write(bb);試圖將bb的內容寫入ObjectOutputStream。這可能不是你想要的。

試試這樣說:

// Create a buffer for the data generated: 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 

ObjectOutputStream out=new ObjectOutputStream(bos); 

out.writeObject(ss3); 

// This makes sure the stream is written completely ('flushed'): 
out.close(); 

// Retrieve the raw data written through the ObjectOutputStream: 
byte[] data = bos.toByteArray(); 

// Wrap the raw data in an ObjectInputStream to read from: 
ByteArrayInputStream bis = new ByteArrayInputStream(data); 
ObjectInputStream in = new ObjectInputStream(bis); 

// Read object(s) re-created from the raw data: 
SomeClass obj = (SomeClass) in.readObject(); 

assert obj.equals(ss3); // optional ;-) 
+0

謝謝你解決.. – Nirav

+4

隨時*接受*我的答案然後:) – JimmyB

+0

我只是沒有試圖關閉/刷新出來,需要將寫入的對象轉換爲ByteArray 非常感謝....: - ) – Nirav

0

ss3.writeExternal(出);

您不應該直接調用該方法。你應該打電話

out.writeObject(ss3); 
相關問題