For saving objects on disc and reading them back in - "persistence". Also used for sending objects "over a wire", eg for Remote Method Invocation (RMI). This is how you do it:
MyClass obj = ...;
File f = new File (filePath);
try
{
// To write an object:
ObjectOutputStream sout =
new ObjectOutputStream (new FileOutputStream (f));
sout.writeObject (obj);
sout.close ();
// To read an object back in:
ObjectInputStream sin =
new ObjectInputStream (new FileInputStream (f));
MyClass copy = (MyClass) sin.readObject ();
sin.close ();
}
catch (IOException ex) { ... }
catch (ClassNotFoundException ex) { ... }
catch (ClassCastException ex) { ... }
MyClass
to be declared as implementing the marker interface java.io.Serializable
. Most of the standard API classes do.serialver
enables you to see the fingerprint value.serialVersionUID
which you give a value, serialisation will use that as the fingerprint - avoids version changes but be careful. WebLogic recommends doing this (they talk about SUID).transient
is not serialised. Deserialisation sets these to 0 or null or false, depending on type.