OO Programming with Java


Serialization

If output format is not important, it is possible to save/load Java objects in binary format.
To proceed, the class, and its attributes (if their are not primitive nor transient), must be "marked" with (i.e. implements) the Serializable interface:

public class Product implements Serializable { ... }
public class Catalog extends ArrayList<Product> 
  implements Serializable {
  ...
  public void saveBinary(String filename) throws Exception {
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
    oos.writeObject(this);
    oos.close();
  }
  public void loadBinary(String filename) throws Exception {
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
    Catalog catalog = (Catalog)ois.readObject();
    for(Product p : catalog)
      this.add(p);
    ois.close();
  } 
}


10 - 12