How to Use Serialized Objects in Java
See Java: Tips and Tricks for similar articles.
What if you created an object in Java and wanted to make it permanent so you can continue working on the object at a later time? The solution is to serialize the object and then write it to a file. When you need the object in the future, you can then read the object back into memory from the file.
Java provides several classes in the java.io package that assist the developer in using serialized objects. To learn how to use serialized objects in Java, follow these seven steps.
- First, you will create the class from which the serialized object will be created. Open your text editor and type in the following Java statements:
The Personclass must implementjava.io.Serializablein order to be serialized. - Save your file as
Person.java. - Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.

- Now you will create the program that serializes the
Personclass. Open your text editor and type in the following Java statements:
The program instantiates the Person object that will be serialized. Next, an OutputObjectStreamobject is created. When you code the constructor argument ofFileOutputStreamandFileInputStream, replace the string containing the path ("c:/JavaStuff") with a directory that exists on your computer. You can retain the file name (Person.ser) or rename it if you prefer. TheObjectOutputStreamconstructor is placed in a "try with resources" statement. Therefore the file will be closed regardless of whether an exception occurs or not. TheIOExceptionis possible during execution of theFileOutputStreamconstructor. The program writes the Person object to the file using theprintObjectmethod. TheObjectInputStreamconstructor is placed in a "try with resources" statement. Therefore the file will be closed regardless of whether an exception occurs or not. TheFileNotFoundExceptionis possible during execution of theFileInputStreamconstructor. TheClassNotFoundExceptionis possible when calling thereadObject. Therefore, a generic catch is provided for both exceptions. The program reads the serialized object using thereadObjectmethod and then displays the contents of the object that is read, i.e., the full name of the person. - Save your file as
UseSerializedObjects.java. - Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.

- Type in the command to run your program and hit Enter.
The output displays the full name stored in the serialized object and then the full name in the retrieved object. The name is identical, verifying that the object was successfully stored in the file.
