一尘不染

Java可序列化对象到字节数组

java

假设我有一个可序列化的类AppMessage

我想byte[]通过套接字将其传输到另一台计算机,从接收的字节重建该计算机。

我怎样才能做到这一点?


阅读 586

收藏
2020-02-28

共1个答案

一尘不染

准备要发送的字节数组:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream 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
  }
}
2020-02-28