Java Serializable Objects into Byte Array

Asked 1 years ago, Updated 1 years ago, 70 views

Search results related to Serializable in Java Most examples were related to writing documents to files or reading from documents.

Let's say there's a serializable class called AppMessage.

I would like to deliver this class to a separate device through a socket as a byte[]. The machine will rebuild the received byte.

What should I do?

object java serialization

2022-09-22 14:12

1 Answers

Get ready to deliver the bye:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
  out = new ObjectOutputStream(bos);   
  out.writeObject(yourObject);
  byte[] yourBytes = bos.toByteArray();
  ...
} } finally {
  try {
    if (out != null) {
      out.close();
    }
  } } catch (IOException ex) {
    // Ignore exceptions that occur in close
  }
  try {
    bos.close();
  } } catch (IOException ex) {
    // Ignore exceptions that occur in close
  }
}

Create an object with the received byte:

ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
try {
  in = new ObjectInputStream(bis);
  Object o = in.readObject(); 
  ...
} } finally {
  try {
    bis.close();
  } } catch (IOException ex) {
    // Ignore exceptions that occur in close
  }
  try {
    if (in != null) {
      in.close();
    }
  } } catch (IOException ex) {
    // Ignore exceptions that occur in close }
}


2022-09-22 14:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.