Java Serializable Object to Byte Array

后端 未结 12 1443
春和景丽
春和景丽 2020-11-22 03:12

Let\'s say I have a serializable class AppMessage.

I would like to transmit it as byte[] over sockets to another machine where it is rebuil

12条回答
  •  滥情空心
    2020-11-22 03:20

    Prepare the byte array to send:

    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
      }
    }
    

    Create an object from a byte array:

    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
      }
    }
    

提交回复
热议问题