【发布时间】:2013-11-27 15:42:48
【问题描述】:
我需要将 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。你忽略了例外