SE450: Java classes: Serialization [21/22] Previous pageContentsNext page

Java supports serialization for any object that implements the java.io.Serializable interface.

// write.java
import java.io.*;
public class write {
  public static void main(String args[])
  {
    try {
      FileOutputStream fos =
        new FileOutputStream("file.out");
      ObjectOutputStream oos =
        new ObjectOutputStream(fos);
      oos.writeObject(new Test("testing", 37));
      oos.flush();
      fos.close();
    }
    catch (Throwable e) {
      System.err.println(e);
    }
  }
}

// read.java
import java.io.*;
public class read {
  public static void main(String args[])
  {
    Test testobj = null;
    try {
      FileInputStream fis =
        new FileInputStream("file.out");
      ObjectInputStream ois =
        new ObjectInputStream(fis);
      testobj = (Test)ois.readObject();
      fis.close();
    }
    catch (Throwable e) {
      System.err.println(e);
    }
    System.out.println(testobj.str);
    System.out.println(testobj.ivalue);
  }
}

// Test.java
public class Test implements java.io.Serializable {
  public String str;
  public transient int ivalue;
  public Test(String s, int i)
  {
    str = s;
    ivalue = i;
  }

Serialization is used by many Java APIs, especially RMI and many J2EE technologies

You can control serialization with more detail using the java.io.Externalizable interface.

package java.io;
public interface Externalizable extends Serializable {
    public void writeExternal(ObjectOutput out) throws IOException;
    public void readExternal(ObjectInput in) throws IOException, 
                             java.lang.ClassNotFoundException;
}

Control whether fields get persisted using transient. You must be aware that an object that is restored from persistence will need its transient fields initialized.

You may find it very useful in your project

Previous pageContentsNext page