Saving the Object to a Flat File

 <  Day Day Up  >  

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 literally flattened, and in a way it is.


One of the things you might have thought about is the fact that an object cannot be saved to a file like a simple variable ”and this is true. In fact, the problem of saving the state of an object has lead to a complete software application industry, which we will 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 determine.

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 consider ”recomposing the object, basically putting it back together.

Another major problem with storing objects relates to the fact that an object can contain other objects. Consider that a Car object might contain objects like Engines and Wheels . When you save the object to a flat file, you need to save 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.

Serializing a File

As an example, consider the following code for a class called Person :

 
 import java.util.*; import java.io.*; class Person implements Serializable{     private String name;     public Person(){     }     public Person(String n){         System.out.println("Inside Person's Constructor");         name = n;     }     String getName() {        return name;     } } 

This class is a simple class that contains only a single attribute representing the name of the person.

The one line of note here is the line that identifies the class as Serializable . If you actually inspect the Java documentation, you will realize that the Serializable interface really does not contain much ”in fact, it is meant solely to identify that the object will be serialized.

 
 class Person implements Serializable{ 

This class also contains a method called getName that returns the name of the object. Beside the Serializable interface, there is really nothing new about this class that we have not seen before. Here is where the interesting stuff starts. We now want to write an application that will write this object to a flat file. The application is called SavePerson , and is as follows :

 
 import java.util.*; import java.io.*; public class SavePerson implements Serializable{     public static void main(String args[]){         Person person = new Person("Jack Jones");         try{             FileOutputStream fos = new FileOutputStream("Name.txt");             ObjectOutputStream oos = new ObjectOutputStream(fos);             System.out.print("Person's Name Written: ");             System.out.println(person.getName());             oos.writeObject(person);             oos.flush();             oos.close();         } catch(Exception e){             e.printStackTrace();         }     } } 

Although some of this code delves into some more sophisticated Java code, we can get a general idea of what is happening when an object gets serialized and written to a file.

Java Code

Although we have not explicitly covered some of the code in this example, such as file I/O, you can get into the code in much greater detail with a few of the books referenced at the end of this chapter.


By now you should realize that this is an actual application. How can you tell this? The fact that the code has a main method in it is a sure tip that this is an actual application. This application basically does three things:

  • Instantiates a Person object

  • Serializes the object

  • Writes the object to the file Name.txt

The actual act of serializing and writing the object is accomplished in the following code:

 
 oos.writeObject(person); 

This is obviously a lot simpler than writing each individual attribute out one at a time. It is very convenient to simply write the object directly to the file

Implementation and Interface Revisited

It is interesting to note that the underlying implementation of the serialization of a file is not quite as simple as the interface used. Remember that one of the most important themes of this book is the concept of separating the implementation from the interface. By providing an intuitive and easy-to-use interface that hides the underlying implementation, life for the user is much easier.

Serializing a file is yet another great example of the difference between the interface and the implementation. The programmer's interface is to simply write the object to the file. You don't care about all of the technical issues required to actually accomplish this feat. All you care about is

  • That you can write the object as an indivisible unit

  • That you can restore the object exactly as you stored it

It's just like using a car. The interface to turn on the car is your key in the ignition, which starts it. Most people do not know or care about the technical issues regarding how things work ”all they care about is that the car starts.

The program SavePerson writes the object to the file Name.txt . The following code restores the object.

 
 import java.io.*; import java.util.*; public class RestorePerson{     public static void main(String args[]){         try{             FileInputStream fis = new FileInputStream("Name.txt");             ObjectInputStream ois = new ObjectInputStream(fis);             Person person = (Person )ois.readObject();             System.out.print("Person's Name Restored: ");             System.out.println(person.getName());             ois.close();         } catch(Exception e){             e.printStackTrace();         }     } } 

The main line of interest here is the code that retrieves the object from the file Name.txt .

 
 Person person = (Person )ois.readObject(); 

It is important to note that the object is reconstructed from the flat file, and a new instance of a Person object is instantiated and initialized . This Person object is an exact replica of the Person object that we stored in the SavePerson application. Figure 11.3 shows the output of both the SavePerson and the RestorePerson applications.

Figure 11.3. Serializing an object.

graphics/11fig03.jpg

Note that in Figure 11.3 the name "Jack Jones," part of the Person object, is stored in the file Name.txt when the file is executed, and then the object is restored when RestorePerson is executed. When the object is restored, we can access the Person attribute.

 <  Day Day Up  >  


Object-Oriented Thought Process
Object-Oriented Thought Process, The (3rd Edition)
ISBN: 0672330164
EAN: 2147483647
Year: 2003
Pages: 164
Authors: Matt Weisfeld

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net