Thursday, June 10, 2010

How to convert an Object into Byte Array


This is a simple program to convert a java object into byte array, This program comes handy when we try to deep clone an object which is my next blog.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;


/**
 * 
 * @author shailesh.chandra
 *
 */
public class ObjectUtil {

 public static void main(String[] args) throws Exception {

  Object object = new Date();

  byte[] byteArray = convertByteArray(object);

  Object readObject = readByteArray(byteArray);

  System.out.println(readObject);

 }

 /**
  * 
  * @param object
  * @return
  * @throws Exception
  */
 private static byte[] convertByteArray(Object object) throws Exception {
  byte[] byteArray;

  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
  objectOutputStream.writeObject(object);

  byteArray = byteArrayOutputStream.toByteArray();
  return byteArray;
 }

 /**
  * 
  * @param byteArray
  * @throws IOException
  * @throws Exception
  */
 private static Object readByteArray(byte[] byteArray) throws Exception {
  ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
  ObjectInputStream objectOutputStream = new ObjectInputStream(byteArrayInputStream);
  Object readObject = objectOutputStream.readObject();

  objectOutputStream.close();
  byteArrayInputStream.close();

  return readObject;
 }

}

No comments: