serialization
■
This Java feature lets you write objects to
files. Serializable objects can be written to files.
■ You make an object serializable by simply having it implement the java.io.Serializable interface. This is just a marker interface. It has no methods and you have no other responsibilities other than to simply implement it. i.e.
import java.io.*;
public class Sample implements Serializable { ... }
■ Java’s object serialization feature lets you write any object that implements the Serializable interface to an OutputStream where it can later be read back. The object read back will be identical to the original object. The resulting stream can go to a file, to a socket, or to the network.
■ To store objects this way you create and write from an ObjectOutputStream object by
chaining it to the appropriate sink stream. For instance, to write objects to a
file you would simply chain the ObjectOutputStream
to a FileOutputStream.
You would then use the writeObject(...)
method of ObjectOutputStream.
■ To read the objects back you simply reverse the process, using ObjectInputStream chained to a FileInputStream, and invoke the readObject( ) method of FileInputStream.
■ Note that since readObject( ) returns an Object, you must always cast all results to their appropriate object type.
■ Any object references in objects that are written cause those other objects to also be written for you automatically. These objects must all be serializable themselves, however. (Most common classes you will encounter in Java have already been made serializable.)
■ Since you are writing to an OutputStream you can intersperse writing your objects with writing primitives using other methods. But then you must read everything back in the same order.
■ The DemoSerializable program below demonstrates serialization by writing three objects to a file using an ObjectOutputStream. It then retrieves them with an ObjectInputStream. They are printed before they are written and printed again after their retrieval. The printout shows how contents of other objects referenced by them - including Vectors containing some Date objects and random String numbers and letters - have not changed. The DemoSerializable program itself was made serializable simply because it is referenced by the SampleObject. All objects referenced by a serializable object which is to be written must also be serializable themselves or you will get a NotSerializableException.
The output of the DemoSerializable program looks like this. The random numbers and letters and times will of course all change with each run:
Objects
before storing:
SampleObject
no. 1 Nos: 123 Ltrs: ABC 8:00:00:000
SampleObject
no. 2 Nos: 456 Ltrs: DEF 8:00:00:100
SampleObject
no. 3 Nos: 789 Ltrs: GHJ 8:00:00:200
Objects
after retrieval at: 8:00:00:300
SampleObject
no. 1 Nos: 123 Ltrs: ABC 8:00:00:000
SampleObject
no. 2 Nos: 456 Ltrs: DEF 8:00:00:100
SampleObject
no. 3 Nos: 789 Ltrs: GHJ 8:00:00:200
import java.io.*;
import java.util.*;
import java.text.*;
public class
DemoSerializable implements Serializable {
SampleObject SO;
SimpleDateFormat sdf = new
SimpleDateFormat(" k:mm:ss:SSS ");
DemoSerializable( ) {
System.out.println("Objects
before storing:\n");
try {
FileOutputStream fos = new
FileOutputStream("object_filename");
ObjectOutputStream oos = new
ObjectOutputStream(fos);
for (int no = 1; no <= 3; no++)
{
String randomNums = String.valueOf((int) (Math.random( )
* 1000));
Date time = new Date( );
SO = new SampleObject(no,
randomNums, randomLetters(3), time);
System.out.println(SO);
oos.writeObject(SO);
}
} catch (IOException e) { }
System.out.println("\n" +
"Objects after retrieval at: " + sdf.format(new Date( )) +
"\n");
try {
FileInputStream fis = new
FileInputStream("object_filename ");
ObjectInputStream ois = new
ObjectInputStream(fis);
for (int x = 0; x <= 2; x++) {
SO = (SampleObject)
ois.readObject();
System.out.println(SO);
}
} catch (Exception e) { }
}
public static void main(String[] args) {
DemoSerializable DS = new
DemoSerializable();
}
public String randomLetters(int n) {
String s =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] c = new char[ n ];
for (int y = 0; y < n; y++) {
int x = (int) (Math.random() *
26);
c[ y ] = s.charAt(x);
}
return new String(c);
}
/*****************************************************************************/
class SampleObject implements Serializable
{
private Vector v = new Vector();
SampleObject(int id, String nos,
String ltrs, Date timeStamp) {
v.addElement(new Integer(id));
v.addElement(nos);
v.addElement(ltrs);
v.addElement(timeStamp);
}
public String toString() {
return("SampleObject no.
" + v.get(0) + " Nos: "
+ v.get(1)
+ " Ltrs: " + v.get(2) + " " + sdf.format(v.get(3)));
}
}
}