How to convert Object to Byte array and byte array to object in java



Prepare bytes to send:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
  out = new ObjectOutputStream(bos);   
  out.writeObject(yourObject);
  byte[] yourBytes = bos.toByteArray();
  ...
} finally {
  out.close();
  bos.close();
}
 
Create object from bytes:
 
ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
try {
  in = new ObjectInputStream(bis);
  Object o = in.readObject(); 
  ...
} finally {
  bis.close();
  in.close();
}