How to convert an object to byte array in java?

Java 8Object Oriented ProgrammingProgramming

To convert an object to byte array

  • Make the required object serializable by implementing the Serializable interface.
  • Create a ByteArrayOutputStream object.
  • Create an ObjectOutputStream object by passing the ByteArrayOutputStream object created in the previous step.
  • Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class.
  • Flush the contents to the stream using the flush() method.
  • Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

Example

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

class Sample implements Serializable {
   public void display() {
      System.out.println("This is a sample class");
   }
}
public class ObjectToByteArray {
   public static void main(String args[]) throws Exception {
      Sample obj = new Sample();
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(bos);
      oos.writeObject(obj);
      oos.flush();
      byte [] data = bos.toByteArray();
   }
}
raja
Published on 09-Jan-2018 12:36:42
Advertisements