Java Reference
In-Depth Information
When an ObjectInputStream object reads a “reset marker" it too clears its record of what has been read,
so that subsequent object read operations are as if the stream started at that point. You can use this to make
sure that multiple versions of the same object exist in the stream when you need it. It's your code, so you
know what you want to do. To make the example work as you want, you can reset the stream before each
output operation after the first call to writeObject() , like this:
PolyLine polygon = new PolyLine(coords);
System.out.println(polygon);
objectOut.writeObject(polygon); // Write first object
objectOut.reset();
// Reset the stream
polygon.addPoint(10., 10.);
System.out.println(polygon); // Add a point
objectOut.writeObject(polygon); // Write second object
objectOut.reset();
// Reset the stream
polygon.addPoint(10., 15.);
System.out.println(polygon); // Add a point
objectOut.writeObject(polygon); // Write third object
If you insert the calls to reset() in the original code and run the example again, you should get the
output you were expecting.
For more complex situations, it is possible to take complete control of the serialization process within
your classes by implementing the Externalizable interface. This is important when the class definition
for the object involves change over time. With careful programming you can accommodate modifications to
classes without invalidating existing serialized objects. A detailed discussion of what is involved in this is
outside the scope of this topic.
SUMMARY
In this chapter you explored how you can write objects to a file and read them back. Making your class seri-
alizable makes it very easy to save your application data in a file. Although what I have discussed is by no
means exhaustive, you now know enough to deal with straightforward object serialization.
EXERCISES
You can download the source code for the examples in the topic and the solutions to the following exer-
cises from www.wrox.com .
1. Define a Person class to encapsulate a person's name and address, with the name and address being
fields of type Name and Address . Write a program to allow names and addresses to be entered from the
keyboard and stored as Person objects in a file. After the file exists new entries should be appended
to the file.
2. Extend the previous example to optionally list all the names and addresses contained within the file
on the command line.
3. Extend the previous example to add an index based on the person's name for each person entered
at the keyboard to locate the corresponding Person object in the object file. The index file contains
Search WWH ::




Custom Search