Java byte array convert from Serializable object

Description

Java byte array convert from Serializable object

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

public class Main {
   public static void main(String[] argv) throws Exception{
      byte[] b = storeObject("demo2s.com");
      //w  w  w  .  j av  a2s.c o m
      Object obj = bytesToObject(b);
      
      System.out.println(obj);
   }
   /**
    * Gets an array of bytes corresponding to the given object.
    *
    * @param object the object to serialize
    * @return an array of bytes.
    * @throws IOException if the object can't be turned into an array of bytes.
    */
   public static byte[] storeObject(final Serializable object) throws IOException {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = null;
      try {
         oos = new ObjectOutputStream(baos);
         oos.writeObject(object);
         oos.flush();
         return baos.toByteArray();
      } finally {
         if (oos != null) {
            oos.close();
         }
         if (baos != null) {
            baos.close();
         }
      }
   }
   
   
   /**
    * Returns a object from the given byte array.
    *
    * @param bytes
    *            array to convert
    * @return object

    */
   public static Object bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
       ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
       ObjectInputStream is = new ObjectInputStream(bais);
       return is.readObject();
   }
   
   
 
}



PreviousNext

Related