Saving and Restoring Serialized Objects
Problem
You need to write and (later) read objects.
Solution
Use the object
stream classes,
ObjectInputStream
and
ObjectOutputStream
.
Discussion
Object serialization is the ability to convert
in-memory objects to an external form that can be sent serially (a
byte at a time) and back again. The “and back again” may
happen at a later time, or in another JVM on another computer (even
one that has a different byte order); Java handles differences
between machines. ObjectInputStream
and
ObjectOutputStream
are specialized stream classes
designed to read and write objects. They can be used to save objects
to disk, as I’ll show here, and are also useful in passing
objects across a network connection, as I’ll show in Section 15.7. This fact was not lost on the designers of
the remote methods invocation, or RMI (see Chapter 22), which uses them for transporting the data
involved in remote method calls.
As you might imagine, if we pass an object such as
MyData
to the writeObject
method, and writeObject
notices that one of the
fields is itself an object such as a String
, that
data will get serialized properly. In other words,
writeObject
works
recursively. So, we will give it an
ArrayList
of data objects. The first is a
java.util.Date
, for versioning purposes. All
remaining objects are of type MyData
.
To be serializable, the data must implement the empty
Serializable
interface. Also, the keyword
transient
can be used
for any data that should not be serialized. ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.