How can I serialize an object into a byte array?

Tim Rohaly

Wrap an ObjectOutputStream around a ByteArrayOutputStream. Serializing an object to the ObjectOutputStream will then store the object in the byte array:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
To restore this object, reverse the process:
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object myObject = ois.readObject();