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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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