Java Reference
In-Depth Information
Objects are written to a file using an ObjectOutputStream object and read from a file
using and ObjectInputStream object.
Objects are written to a file by calling the writeObject() method for the
ObjectOutputStream object corresponding to the file.
Objects are read from a file by calling the readObject() method for the
ObjectInputStream object corresponding to the file.
When necessary, for instance if a superclass is not serializable, you can implement the
readObject() and writeObject() methods for your classes.
A good horse cannot be of a bad color.
Exercises
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. Once 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 will contain entries of type IndexEntry each of which encapsulates a name and a
file position in the object file. The index file should be a separate file from the original file
containing Person objects.
Note: You will probably find it easiest to delete the previous file before you run this example
so that the object file can be reconstructed along with the index file. You can't get the file
position in an object stream in the same way as you can with a channel. However, you can use
the sequence number for an object as the index - the first object being 1, the second being 2,
and so on.
4.
Use the index file to provide random direct access to the object file for querying random
names entered from the keyboard. Entering a name from the keyboard should result in the
address for the individual, or a message indicating the entry is not present in the file. The
process will be to first search the index file for an object with a name field matching the
keyboard entry. When an IndexEntry is found, you use the sequence number it contains to
retrieve the appropriate Person object.
Search WWH ::




Custom Search