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); }}