Object Serialization Example

   

This simple examples of serialization stores and retrieves an instance of the Date class to and from a file. To do this without object serialization, you would probably do something on the order of getTime() and write the resulting long integer to the file. However, with object serialization the process is much easier.

Listing 22.2 shows a utility class called OurDateUtility that has two static methods : writeDateToFile and readDateFromFile. These methods write and read a Date object using serialization. Remember, to serialize an object to a stream, the class must be serializable. Fortunately, if you look at the Date class, it implements the Serializable interface already. One important thing to watch is that all the data within the class must be serializable. If the attributes are primitives, you don't have to worry. If the attributes are references to other objects, make sure those other objects are serializable.

Listing 22.2 OurDateUtility.java ” Utility Class for Date Serialization
 import java.util.Date; import java.io.*; public class OurDateUtility {   /**    * Static utility method that takes an instance of the Date class and a    * filename and serializes the Date instance to the file */   public static void writeDateToFile( Date dateInstance, String fileName )   {     try     {       // Create the object stream on an output file stream       FileOutputStream fileStream = new FileOutputStream( fileName, false );       ObjectOutputStream objectStr = new ObjectOutputStream( fileStream );       // write out the object       objectStr.writeObject( dateInstance );       // Close the resources       objectStr.close();       fileStream.close();     }     catch( FileNotFoundException ex )     {       ex.printStackTrace();       System.out.println( "Could not create the file for some reason" );       System.exit(-1);     }     catch( IOException ex )     {       ex.printStackTrace();       System.out.println(  "There was a problem writing the object to the stream" ); System.exit(-1);     }   }   /**    * Static utility method that takes a filename and deserializes * a date instance from it and returns the Date instance    */   public static Date readDateFromFile( String fileName )   {     Date dateFromFile = null;     try     {       // Create an Object input stream on an input file stream       FileInputStream in = new FileInputStream( fileName );       ObjectInputStream objectInStr = new ObjectInputStream( in );       // read in the object       Object obj = objectInStr.readObject();       // Double check that it is the right type before casting       if ( obj instanceof Date )       {         dateFromFile = (Date)obj;       }     }     catch( ClassNotFoundException ex )     {       ex.printStackTrace();     }     catch( FileNotFoundException ex )     {       ex.printStackTrace();     }     catch( IOException ex )     {       ex.printStackTrace();     }     return dateFromFile;   } } 

Look at the code in Listing 22.2. First, notice that the program creates a FileOutputStream. To do any serialization to a file, it is first necessary to declare a FileOutputStream to which you will attach the ObjectOutputStream.

After you have established a stream, you must create an ObjectOutputStream with it. The ObjectOutputStream contains all the necessary methods to serialize any primitive or object and to write it to the stream.

Listing 22.3 shows a test class that uses the OurDateUtility class to perform serialization.

Listing 22.3 OurDateUtilityTest.java ” A Class for Testing OurDateUtility
 import java.util.Date; public class OurDateUtilityTest {   public static final String DATE_FILE = "datefile.dat";   public static void main(String[] args)   {     // Create an instance of the Date class and print out its value     Date aDate = new Date( System.currentTimeMillis() );     System.out.println( "Serializing date: " + aDate.toString() );     // Call the utility class to serialize it     OurDateUtility.writeDateToFile(  aDate, OurDateUtilityTest.DATE_FILE );     // Deserialize the Date object from the file and print its value     Date dateFromFile =  OurDateUtility.readDateFromFile( OurDateUtilityTest.DATE_FILE ); if ( dateFromFile != null )     {       System.out.println(  "Deserializing date: " + dateFromFile.toString() );     }   } } 

When you run the OurDateUtilityTest class, the output should look similar to this:

 C:\jdk1.3se_book\classes>java OurDateUtilityTest Serializing date: Tue Jul 11 20:31:05 PDT 2000 Deserializing date: Tue Jul 11 20:31:05 PDT 2000 C:\jdk1.3se_book\classes> 

The actual date value will be different, but hopefully the value that was serialized to the file is the same after being deserialized.

Troubleshooting Tip

If you experience a ClassNotFoundException during the deserialization process, see " ClassNotFoundException Thrown During Deserialization" in the "Troubleshooting" section at the end of this chapter.


The file that was created to hold the serialized object is called datefile.dat . Note that the name could have been any legal file named for the operating system. It didn't have to have an extension of .dat, it could have been anything. It should still be on the file system. The file is not removed by deserializing the object or by the utility class. If you open the file with a text editor, you will see something that looks mostly like garbage. However, a closer inspection reveals that this file contains several interesting things. The text that looks like garbage characters is actually what the serialization used to store information about the class, such as the value of the fields and the class signature that was discussed earlier.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

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