Serialization to Byte Array

Serialization to Byte Array

How can I convert a class instance to a byte array and thensubsequently reconstruct the original class from the byte array?

Java’s Object Serialization API allows you to write class instancesto streams. In order to store a class instance in a byte arrayyou can wrap a ByteArrayOutputStream with an ObjectOutputStream.

To read a class instance from a byte array you can wrap anObjectInputStream with a ByteArrayInputStream. You justhave to remember that all serializable objects must implementthe Serializable interface. The following example demonstrateshow to do this.

import*;public class ByteSerialize {  public static void main(String[] args) {    Integer write, read;    ObjectOutputStream out;    ObjectInputStream in;    ByteArrayOutputStream byteStream;    byte[] bytes;    write = new Integer(5);    System.out.println("write: " + write);    try {      byteStream = new ByteArrayOutputStream();      out = new ObjectOutputStream(byteStream);      out.writeObject(write);      out.close();      // Byte representation of integer      bytes = byteStream.toByteArray();      in = new ObjectInputStream(new ByteArrayInputStream(bytes));      read = (Integer)in.readObject();      in.close();    } catch(IOException ioe) {      ioe.printStackTrace();      return;    } catch(ClassNotFoundException cnfe) {      cnfe.printStackTrace();      return;    } catch(ClassCastException cce) {      cce.printStackTrace();      return;    }    System.out.println("read : " + read);  }}
See also  Does It Make Sense to Splurge on a Laptop?

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist