Serialization

Back Up Next

 

Serialization
An "automatic" way to save and restore Java Objects and primitive data types
Serialization saves fields that are non-transient, non-static, and non-private
Objects are read with the readobject method and written with the writeObject method
Primitives are read with the methods of DataInput and written with the methods of DataOutput
//
// Serialize today's date to a file.
//
FileOutputStream fos = new FileOutputStream("C:\\DATA\\TEMP\\TODAY.OBJ");
ObjectOutput oo = new ObjectOutputStream(fos);
oo.writeObject("Today");
oo.writeObject(new Date());
oo.flush();
//
// Deserialize a string and date from a file.
//
FileInputStream fis = new FileInputStream("C:\\DATA\\TEMP\\TODAY.OBJ");
ObjectInputStream ois = new ObjectInputStream(fis);
String today = (String)ois.readObject();
Date date = (Date)ois.readObject();
Caveat: Only Objects that implement the Serializable and Externalizable interfaces can be (de)serialized.
Additional caveats include: Can't serialize inner classes
Cool things Serialization enable: sending Java Objects perfectly to remote machines via the network
Full details at http://web2.java.sun.com/products/jdk/1.3/docs/guide/serialization/spec/serialTOC.doc.html