Programming and Problem Solving with Java

(やまだぃちぅ) #1
7.8 Output and Input of Objects | 355

work for the programmer. Fortunately, Java provides a way to save objects and read them back
again without requiring all of this work. Saving an object with this approach is called serial-
izingthe object.
The basic unit of data in the FileReaderand FileWriterclasses is the character. The
BufferedReaderand PrintWriterclasses include methods that make reading and writing
strings easier, but the basic unit remains the character. Java provides two classes for which
the object is the basic unit of data: ObjectOutputStream(derived from OutputStream) and
ObjectInputStream(derived from InputStream). To write an object to a file, we use the writeObject
method of the ObjectOutputStreamclass. To read objects from a file, we use the readObject
method of the ObjectInputStreamclass.
How can this be? Java uses the Unicode character set; all the characters take
up the same number of bits. Untold numbers of objects exist, whose struc-
tures vary in size and shape. Writing would seem to be easy, but how do we fig-
ure out how the bytes group when inputting the object? Fortunately, we don’t
have to know. One of the most important features in thejava.iopackage is
the ability to convert an object into a stream of bytes that can later be converted
back into a copy of the original object. This translation from object to bytes is
calledserializing. The reverse translation is calleddeserializing. We do not need
to understand how Java performs this conversion; we just have to know how
to use this feature.
Let’s examine the syntax and semantics of writing objects through the use of a pair of
application programs. The first creates an object and writes it out; the second reads the ob-
ject back in and writes it to the screen. Let’s use the class Namefrom Chapter 4 for this example.
Recall that Namehas three data fields: first,middle, and last. To serialize objects of the class
Name, we need to add the words implementsSerializablebeside the class name. Here is the doc-
umentation (a list of the methods) for Nameto refresh your memory:


public className implementsSerializable
// This class defines a name consisting of three parts
{
// Constructors
publicName() throwsIOException
publicName(String firstName, String lastName, String middleName)


// Knowledge methods
publicString knowFirstName()
publicString knowMiddleName()
publicString knowLastName()

// Additional observer methods that return a formatted name
publicString firstLast()

Serializing Translating an
object into a stream of bytes
Deserializing Translating a se-
rialized stream of bytes back
into the original object
Free download pdf