假设我有一个可序列化的类AppMessage。
AppMessage
我想byte[]通过套接字将其传输到另一台计算机,从接收的字节重建该计算机。
byte[]
我怎样才能做到这一点?
准备要发送的字节数组:
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 } }