Convert Serializable object to byte array. - Android java.lang

Android examples for java.lang:array convert

Description

Convert Serializable object to byte array.

Demo Code

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import android.util.Log;

public class Main {

  private static final String TAG = "ArrayUtil";

  /**/*  w  w  w.  j a va  2 s  .  c  o m*/
   * Convert Serializable object to byte array.
   * 
   * @param o
   * @return
   */
  public static byte[] objectToByteArray(Serializable o) {
    byte[] result = null;
    try {
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
      objectOutputStream.writeObject(o);

      result = byteArrayOutputStream.toByteArray();

      byteArrayOutputStream.close();
      objectOutputStream.close();
    } catch (Exception e) {
      Log.e(TAG, "objectToByteArray() error: " + e);
    }
    return result;
  }

  /**
   * Convert Serializable object to byte array.
   * 
   * @param o
   * @return
   */
  public static byte[] objectToByteArray(Serializable... o) {
    byte[] result = null;
    try {
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
      for (int i = 0; i < o.length; i++) {
        objectOutputStream.writeObject(o[i]);
      }
      result = byteArrayOutputStream.toByteArray();

      byteArrayOutputStream.close();
      objectOutputStream.close();
    } catch (Exception e) {
      Log.e(TAG, "objectToByteArray() error: " + e);
    }
    return result;
  }

}

Related Tutorials