Java Reference
In-Depth Information
4.6
Serialisation [U.S. Spelling Seriali
z
ation]
As seen in the preceding sections, transferring data of the primitive types to and
from disc fi les is reasonably straightforward. Transferring string data presents a
little more of a challenge, but even this is not a particularly onerous task. However,
how do we go about transferring objects of classes? (
String
is a class, of course, but
it is treated rather differently from other classes.) One way of saving an object to a
fi le would be to decompose the object into its constituent fi elds (strings and num-
bers) and write those individual data members to the fi le. Then, when reading the
values back from the fi le, we could re-create the original objects by supplying those
values to the appropriate constructors. However, this is a rather tedious and long-
winded method. In addition, since the data members of an object may themselves
include other objects (some of whose data members may include further objects,
some of whose members…), this method would not be generally applicable.
Unlike other common O-O languages, Java provides an inbuilt solution:
seriali-
sation
. Objects of any class that implements the Serializable interface may be trans-
ferred to and from disc fi les as whole objects, with no need for decomposition of
those objects. The
Serializable
interface is, in fact, nothing more than a marker to
tell Java that objects of this class may be transferred on an object stream to and from
fi les. Implementation of the
Serializable
interface need involve no implementation
of methods. The programmer merely has to ensure that the class to be used includes
the declaration '
implements Serializable
' in its header line.
Class
ObjectOutputStream
is used to save entire objects directly to disc, while
class
ObjectInputStream
is used to read them back from disc. For output, we wrap
an object of class
ObjectOutputStream
around an object of class
FileOutputStream
,
which itself is wrapped around a
File
object or fi le name. Similarly, input requires
us to wrap an
ObjectInputStream
object around a
FileInputStream
object, which in
turn is wrapped around a
File
object or fi le name.
Examples
(i) ObjectOutputStream outStream =
new ObjectOutputStream(
new FileOutputStream("personnel.dat"));
(ii) ObjectInputStream inStream =
new ObjectInputStream(
new FileInputStream("personnel.dat"));
Methods
writeObject
and
readObject
are then used for the actual output and
input respectively. Since these methods write/read objects of class
Object
(the ulti-
mate superclass), any objects read back from fi le must be
typecast
into their origi-
nal class before we try to use them. For example:
Personnel person = (Personnel)inStream.readObject();
//(Assuming that inStream is as declared above.)
Search WWH ::
Custom Search