io

Serialize arbitrary objects

public static byte[] serializeObject(Serializable object) throws Exception {
  ByteArrayOutputStream baos = null;
  ObjectOutputStream oos = null;
  byte[] res = null;
  
  try {
   baos = new ByteArrayOutputStream();
   oos = new ObjectOutputStream(baos);
   
   oos.writeObject(object);
   oos.flush();
   
   res = baos.toByteArray();
  
  } catch (Exception ex) {
   throw ex;
  } finally {
   try {
    if(oos != null)
     oos.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  
  return res;
 }
 
public static Serializable deserializeObject(byte[] rowObject) throws Exception {
  ObjectInputStream ois = null;
  Serializable res = null;
  
  try {
   
   ois = new ObjectInputStream(new ByteArrayInputStream(rowObject));
   res = (Serializable) ois.readObject();
  
  } catch (Exception ex) {
   throw ex;
  } finally {
   try {
    if(ois != null)
     ois.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
   
  }
  
  return res;
  
 }

Related Article:

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button