227
Saving the Object to a Flat File
Saving the Object to a Flat File
In this section, we will use a flat file to illustrate object persistence. I define a flat file as a
simple file managed by the operating system.This is a very simple concept, so don’t get
too caught up in this description.
Flat Files
Many people do not like to use the term flat file. The word flat implies that the object is liter-
ally flattened, and in a way it is.
One of the issues you might have considered is the fact that an object cannot be saved to
a file like a simple variable—and this is true. In fact, this problem of saving the state of an
object has spawned a major segment of the software product industry, which we discuss at
length later in this chapter. Normally, when you save a number of variables to a file, you
know the order and type of each variable, and then you simply write them out to the file.
It could be a comma delimited file or any other protocol that you may decide to imple-
ment.
The problem with an object is that it is not simply a collection of primitive variables.
An object can be thought of as an indivisible unit that is composed of a number of parts.
Thus, the object must be decomposed into a unit that can be written to a flat file.After
the object is decomposed and written to a flat file, there is one major issue left to con-
sider—reconstituting the object, basically putting it back together.
Another major problem with storing objects relates to the fact that an object can con-
tain other objects. Consider that a
Car object might contain objects like Engines and
Wheels.When you save the object to a flat file, you must consider saving the entire object,
Car, Engines, and the like.
Java has a built-in mechanism for object persistence. Like other C-based languages, Java
largely uses the concept of a stream to deal with I/O.To save an object to a file, Java writes
it to the file via a Stream.To write to a Stream, objects must implement either the
Serializable or Externalizable interface.
The obvious downside to this approach is that the solution is proprietary—you must
be using Java to get this to work. In fact, Java must be on both sides of the “pipe.”Another
more portable approach to this problem is to create an XML document as the intermedi-
ate file and decompose and reconstitute an object using open XML technologies.
We cover both approaches in this chapter. First, Java will be used to demonstrate the
Java serialization technology, and then we will use an XML strategy to implement an
.NET example in both Visual Basic and C#.
Serializing a File
As an example, consider the following code for a class called Person:
package Serialization;
import java.util.*;
import java.io.*;