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();
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.