Share this page 

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 serialize an ArrayList to a file and we reload it.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class SerializeDemo {

  @SuppressWarnings("unchecked")
  public static void main(String args[]) throws IOException, ClassNotFoundException {
    ArrayList <String> arraySerialized = new ArrayList<String>();
    arraySerialized.add("element 1");
    arraySerialized.add("element 2");
    arraySerialized.add("element 3");
    arraySerialized.add("element 4");
    arraySerialized.add("element 5");
    System.out.println("ArrayList to be serialized : " + arraySerialized );
    System.out.println("serializing the array");
    ObjectOutputStream oos = null;
    try {
      FileOutputStream fout = new FileOutputStream("c:\\temp\\thearraylist.dat");
      oos = new ObjectOutputStream(fout);
      oos.writeObject(arraySerialized);
    }
    finally {
      if (oos!=null) oos.close();
    }

    // deserialize the ArrayList
    ArrayList <String> arrayUnserialized = new ArrayList<String>();
    System.out.println("unserializing the array");
    ObjectInputStream ois = null;
    try {
      FileInputStream fin = new FileInputStream("c:\\temp\\thearraylist.dat");
      ois = new ObjectInputStream(fin);
      arrayUnserialized = (ArrayList) ois.readObject();
      ois.close();
    }
    finally {
      if (ois!=null) ois.close();
    }
    System.out.println("ArrayList unserialized : " + arrayUnserialized);
  }
}

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.