Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata