Tuesday, September 25, 2012

byte[] to Object in java

If data must be sent over network, it is needed to send  data as byte stream. In these cases, it can be used object serialize method as follows. Below method can be used to convert Object to byte stream. 

public static byte[] serialize(Object obj) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}


Below deserialize method can be used to converted stream back to Object. If Object is specific use Object casting methods further.

public static Object deserialize(byte[] data) {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();
}


NOTE :- This can be avoided by using Java RMI technology.