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.

Категории