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 ...

Get Special Edition Using Java 2 Standard 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.