O'Reilly logo

Java I/O, 2nd Edition by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 13. 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 an 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 that reads an object from a stream. ObjectInputStream and ObjectOutputStream implement the DataInput and DataOutput interfaces respectively so they can also write primitive data types such as ints, floats, and doubles, 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required