Java Serializable load from byte array

Description

Java Serializable load from byte array

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 java.util.Arrays;

public class Main {
   public static void main(String[] argv) throws Exception{
      byte[] b = storeObject("demo2s.com");
      //from w w w. j av a  2 s . com
      Object obj = bytesToObject(b);
      
      System.out.println(obj);
   }

   

   /**
    * 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();
   }
   
   
   /**
    * 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();
         }
      }
   }
}



PreviousNext

Related