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
這是我轉換爲字節數組的類。
不要吞下你的異常,處理它們。 –
最新錯誤?使用try ... catch ... finally。你忽略了例外 – Nishant