Java可序列化对象到ByteArray假设我有一个可序列化的类AppMessage.我想把它作为byte[]从套接字到另一台机器,从接收到的字节重建它。我怎样才能做到这一点?
3 回答
Qyouu
TA贡献1786条经验 获得超11个赞
ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutput out = null;try {
out = new ObjectOutputStream(bos);
out.writeObject(yourObject);
out.flush();
byte[] yourBytes = bos.toByteArray();
...} finally {
try {
bos.close();
} catch (IOException ex) {
// ignore close exception
}}ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);ObjectInput in = null;try {
in = new ObjectInputStream(bis);
Object o = in.readObject();
...} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
// ignore close exception
}}添加回答
举报
0/150
提交
取消
