Saturday, February 7, 2009

Convert a serializable object to byte array and vise versa

Convert a serializable object to byte array and vise versa using apache.commons.codec

/**
*
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.binary.BinaryCodec;

/**
* @author jijo
*This class is used to convert object to byte array and wise verse
*/
public class ObjectByteArray {
/**
* This method is used to convert object to Byte array
* @param object
* @return
* @throws IOException
* @throws EncoderException
*/
public static byte[] getBytes(Serializable object) throws IOException, EncoderException {
byte[] data = null ;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bytes);
oos.writeObject(object);
oos.flush();
oos.close();
data = bytes.toByteArray();
BinaryCodec binaryCodec = new BinaryCodec();
byte[] byteArr = binaryCodec.encode(data);
return byteArr;
}
/**
* This method is used to convert byte array to object
* @param bytes
* @return
* @throws Exception
*/
public static Object restoreBytes(byte[] bytes) throws Exception {
byte[] data = null;
BinaryCodec binaryCodec =new BinaryCodec();
data = binaryCodec.decode(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bais);
Object object = ois.readObject();
ois.close();
return object;
}
}

No comments: