Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Nov 5, 1999

Serialization to Byte Array

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

Answer:
Java's Object Serialization API allows you to write class instances to streams. In order to store a class instance in a byte array you can wrap a ByteArrayOutputStream with an ObjectOutputStream.

To read a class instance from a byte array you can wrap an ObjectInputStream with a ByteArrayInputStream. You just have to remember that all serializable objects must implement the Serializable interface. The following example demonstrates how 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);

  }
}

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date