2013-11-27 87 views
1

我需要將Object作爲字節數組發送到另一個方法,該方法本身將從對象返回另一個字節數組。將類轉換爲字節數組和反之亦然時出錯?

這是我有調用方法的代碼:

byte[] bytesArray; 
Gato gatito = null; 
Gato gato = new Gato(); 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
ObjectOutput out = null; 

try { 

out = new ObjectOutputStream(bos); 
out.writeObject(gato); 
bytesArray = bos.toByteArray(); 
} 

finally { 
out.close(); 
bos.close(); 
} 

System.out.println("Gatito es nulo? "+gatito==null); 
byte[] huntedCat = cliente.method(bytesArray); 

ByteArrayInputStream bis = new ByteArrayInputStream(huntedCat); 
ObjectInput in = null; 
try { 
in = new ObjectInputStream(bis); 
gatito = ((Gato)in.readObject()); 
} finally { 
bis.close(); 
in.close(); 
} 

System.out.println(gatito.nombre); 


} 

所以這就是所謂的方法,實際執行完全相同的操作:

public byte[] method(byte[] something) { 

    byte[] bytesArray = null; 
    Gato gato = new Gato(); 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    ObjectOutput out = null; 

    try { 

    out = new ObjectOutputStream(bos); 
    out.writeObject(gato); 
    bytesArray = bos.toByteArray(); 
    out.close(); 
    bos.close(); 

    } 
    catch(IOException e) { 

    } 

    return bytesArray; 
} 

我總是得到一個錯誤,所以程序暫停和getMessage異常說Gato這是我轉換爲字節數組的類。

+1

不要吞下你的異常,處理它們。 –

+0

最新錯誤?使用try ... catch ... finally。你忽略了例外 – Nishant

回答

2

難道你的Gato班不執行Serializable

請參閱:Serializable(JavaDocs)

相關問題