Java Reference
In-Depth Information
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 might 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 is 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.
• WHAT YOU LEARNED IN THIS CHAPTER
TOPIC
CONCEPT
Making a
Class Seri-
alizable
To make objects of a class serializable the class must implement the
Serializable
interface.
Class Ver-
sion ID
The deserialization process checks the version ID for the class definition used to read objects to verify that
the class is the same as that used when the file was written. You should define explicitly the variable
serialVersionUID
as static and final in your serializable classes to ensure deserialization works without
difficulty.
Base
Classes
Not Serial-
izable
If a class has a superclass that does not implement the
Serializable
interface then the superclass must
have a public default constructor if it is to be possible to serialize the class.
Object
Streams
Objects are written to a file using an
ObjectOutputStream
object and read from a file using an
Ob-
jectInputStream
object.
Creating
Object
Streams
You can create an object input stream by calling the
newInputStream()
method for a
Path
object. Calling
the
newOutputStream()
method for a
Path
object creates an object output stream.
Writing
Objects to
a File
Objects are written to a file by calling the
writeObject()
method for the
ObjectOutputStream
object
corresponding to the file.
Reading
Objects
from a File
Objects are read from a file by calling the
readObject()
method for the
ObjectInputStream
object
cor-
responding
to the file.
Writing
Versions of
an Object
To write different versions of the same object to an object output stream you need to call the
reset()
method for the stream before you write each object version after the first. If you don't call reset, only the
first version of the object is written to the stream and subsequent versions are written as handles referen-
cing the first object instance that was written.