Chapter 11. Object Serialization

The last several chapters have shown you how to read and write Java’s fundamental data types (byte, int, String, etc.). However, there’s been one glaring omission. Java is a fully object-oriented language; and yet aside from the special case of strings, you haven’t seen any general-purpose methods for reading or writing objects.

Object serialization, first used in the context of Remote Method Invocation (RMI) and later for JavaBeans, addresses this need. The java.io.ObjectOutputStream class provides a writeObject() method you can use to write a Java object onto a stream. The java.io.ObjectInputStream class has a readObject() method you can use to read an object from a stream. In this chapter you’ll learn how to use these two classes to read and write objects as well as how to customize the format used for serialization.

Reading and Writing Objects

Object serialization saves an object’s state in a sequence of bytes so that the object can be reconstituted from those bytes at a later time. Serialization in Java was first developed for use in RMI. RMI allows an object in one virtual machine to invoke methods in an object in another virtual machine, possibly in a different computer on the other side of the planet, by sending arguments and return values across the Internet. This requires a way to convert those arguments and return values to and from byte streams. It’s a trivial task for primitive data types, but you need to be able to convert objects as ...

Get Java I/O 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.