Professional Java.JDK.5.Edition (Wrox)
.pdfPersisting Your Application
Using Files
Saving an application’s state is one of the most important qualities necessary to reuse an application. Imagine what life would be like if word processors could not save documents, or image manipulation programs could not save images! If a user had to retype a document every time he or she wanted to print it, many tasks now common to computers would probably still be done by hand. An end user calls the ability of a word processing application to save its state saving a document. To the software developer, saving a document means saving the internal memory state of the word processing application in such a way as to be able to recreate it exactly as it was left at a future point in time. In this chapter, there will be more references to persisting an application’s state than to saving a document, but in reality, they are similar phrases — the former is simply more precise (since an application’s state can be saved in other ways than to a file).
Different applications need to save different pieces of information to disk to properly recreate their state. Some applications only need to save their configuration settings to disk, as they may save their other data to a database (see the subsequent chapter to see how to persist your application’s data to a database). A typical single-user application such as a word processor or image manipulation program will need to save its state to files (for example, Word documents or JPEG images). Java provides a couple built-in mechanisms for saving or serializing data to files. The two major APIs in the JDK for persisting application data to disk are: the Java Serialization API for generic serialization and the XMLEncoder/Decoder API for serializing Java Bean components. These two APIs will be discussed in depth in this chapter along with the Java API for XML Binding (JAXB). JAXB provides the ability to read and write data to user-defined XML formats. Each of these three APIs has a different approach to serialization and as such should be used in different circumstances. In this chapter, you will first look at how application data is structured in memory, and then apply the Java Serialization API, the XMLEncoder/Decoder API, and the JAXB API to actually serialize the data to disk. These three APIs are a great foundation for persisting your application’s data to disk.