Real'sHowTo AddThis Feed Button
Custom Search

Serialize an ObjectTag(s): Language


To serialize an object, it must implements the Serializable interface. The object needs 2 functions with these signatures
private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException; 
Many standard Java objects already implements the Serializable interface so there is almost nothing to do.

In the following snippet, we use a Vector to simulate a Queue.

First the Queue state is saved to a file.

Then rename main to main_serialize and main_reload to main and compile. Now the snippet read the file to reload the Queue from the data previously saved.

 import java.util.Vector;
 import java.io.*;

 public class Queue extends Vector {
  /*
  ** FIFO
  */
  Queue() {
  super();
  }
 
 void put(Object o) {
  addElement(o);
  }

 Object get() {
  if (isEmpty()) return null;
    Object o = firstElement();
    removeElement(o);
    return o;
  }

 Object peek() {
  if (isEmpty()) return null;
    return firstElement();
    }
    
 public static void main(String args[]) {
  Queue theQueue;
  
  theQueue = new Queue();
  theQueue.put("element 1");
  theQueue.put("element 2");
  theQueue.put("element 3");
  theQueue.put("element 4");
  System.out.println(theQueue.toString());
  
  // serialize the Queue
  System.out.println("serializing theQueue");
  try {
      FileOutputStream fout = new FileOutputStream("thequeue.dat");
      ObjectOutputStream oos = new ObjectOutputStream(fout);
      oos.writeObject(theQueue);
      oos.close();
      }
   catch (Exception e) { e.printStackTrace(); }
  }
  
  public static void main_load(String args[]) {
    Queue theQueue;
    
    theQueue = new Queue();
    
    // unserialize the Queue
    System.out.println("unserializing theQueue");
    try {
        FileInputStream fin = new FileInputStream("thequeue.dat");
        ObjectInputStream ois = new ObjectInputStream(fin);
        theQueue = (Queue) ois.readObject();
        ois.close();
        }
     catch (Exception e) { e.printStackTrace(); }
    System.out.println(theQueue.toString());     
    }
}

Note : See this How-to to serialize using XML format.


If you need to serialize and manipulate huge objects, take a look at this open-source project.

joafip( java data object persistence in file ) at http://joafip.sourceforge.net.



blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2013
[ home ]