Thursday, November 19, 2009

Convert a Serializable Object to a Byte Array

Today's challenge is to take an object that  implements Serializable  (java.io.Serializable) and converts it to a byte array so it can be stored either in a table, file or sent over the wire. Not to hard, the whole idea is to make sure the object implements Serializable and the magic happens on the WriteObject call.


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;


public class util {
public static byte[] SerializeObject(Object o)
{
  byte [] buffer = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
buffer = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
  }

}

No comments:

Post a Comment