devxlogo

Serialization to Byte Array

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

Answer:
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 java.io.*;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);  }}

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Seasoned Architects Evaluate New Tech

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.