Friday, February 20, 2009

Java Serialization Snippets

Object serialisation is the process of saving an object's state to a sequence of bytes. De-serialisation is the process of rebuilding the object from those bytes later.

The object to be serialised must implement the Serializable interface or inherit it. If you don't want fields in the object serialised mark them as transient.

Serializing an Object

//the object to serialize
Date date=new Date() ;

//the file to serialize to
String filename="date.ser";

//write the object to file
FileOutputStream fos=new FileOutputStream(filename);
BufferedOutputStream bos=new BufferedOutputStream(fos);
ObjectOutputStream outputStream=new ObjectOutputStream(bos);
outputStream.writeObject(date);
outputStream.flush();
outputStream.close();
De-Serializing an Object

//the file containing the serialized object
String filename="date.ser";

//read the object from the file
FileInputStream fis=new FileInputStream(filename);
BufferedInputStream bis=new BufferedInputStream(fis);
ObjectInputStream inputStream=new ObjectInputStream(bis);
Date date=(Date)inputStream.readObject();
inputStream.close();

//print the object
System.out.println(date);
Determining the Size of an Object
//the object to measure
Date date=new Date() ;

//write it out to a byte array
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(baos);
oos.writeObject(date);
oos.close();
byte[] ba=baos.toByteArray();
baos.close();

//print size
System.out.println(ba.length);
or you can serialize the object to a file and measure the size of the file.

2 comments:

  1. Anonymous6:07 PM

    you have a nice site. thanks for sharing this site. there are various kinds of ebooks are available here

    http://feboook.blogspot.com

    ReplyDelete
  2. Hello this is a nice site.Do you also do C programming?
    http://www.mycsnippets.blogspot.com/

    ReplyDelete

Note: Only a member of this blog may post a comment.