12.1. Storing Objects in a File

The process of storing and retrieving objects in an external file is called serialization. Writing an object to a file is referred to as serializing the object, and reading an object from a file is called deserializing an object. Serialization is concerned with writing objects and the fields they contain to a stream, so this excludes static members of a class. Static fields will have whatever values are assigned by default in the class definition. Note that an array of any type is an object and can be serialized, even an array of values of a primitive type, such as type int or type double.

I think you will be surprised at how easy this is. Perhaps the most impressive aspect of the way serialization is implemented in Java is that you can generally read and write objects of almost any class type, including objects of classes that you have defined yourself, without adding any code to the classes involved to support this mechanism. For the most part, everything is taken care of automatically.

Two classes from the java.io package are used for serialization. An ObjectOutputStream object manages the writing of objects to a file, and reading the objects back is handled by an object of the class ObjectInputStream. As you saw in Chapter 8 and as Figure 12-1 illustrates, these are derived from OutputStream and InputStream, respectively.

Figure 12.1. Figure 12-1

The ObjectInput and ObjectOutput interfaces extend the DataInput and DataOutput interfaces that ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition 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.