Serialization is a powerful tool. It's what allows us to store objects on disk and reconstruct them in memory when necessary -- perhaps when the program restarts. For anyone who wants to move beyond the run-and-forget type of programs, serialization is essential. We can serialize objects to create a sense of persistence in our programs so that the information we gather is not lost, or forgotten, when our program ends. Let's take a look at how to implement serialization in Java
The folks over at Oracle define serializable objects like so:
To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object.
There may be many reasons for a programmer to serialize an object, but we will focus on the reason of storing it in a file to be accessed later.
In this case, deserialization is then the process of reverting the serialized form of an object into a copy of the object to use as expected. You can serialize any object that is an instance of a class that either implements java.io.Serializable
interface or its subinterface, java.io.Externalizable
itself or is the subclass of a class that does.
The Application
We're going to build a simple phone book app in the console. The program will allow a user to add contacts to their phone book, view their contacts, delete contacts, and save their contacts to a file for later. When the user ends the program and relaunches it later, they will be asked for the name of the file they want to load their phone book contacts from. If a file containing the serialized form of the phone book's contacts exists, the phone book will be loaded from disk and made available to the user for manipulation.
The code related to this article can be found here.
Continue reading %Java Serialization: Building a Persistent Phone Book%
by Lincoln Daniel via SitePoint
No comments:
Post a Comment