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.
Personclass must implement
java.io.Serializablein order to be serialized.
Personclass. Open your text editor and type in the following Java statements:
OutputObjectStreamobject is created. When you code the constructor argument of
FileInputStream, 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. The
ObjectOutputStreamconstructor is placed in a "try with resources" statement. Therefore the file will be closed regardless of whether an exception occurs or not. The
IOExceptionis possible during execution of the
FileOutputStreamconstructor. The program writes the Person object to the file using the
ObjectInputStreamconstructor is placed in a "try with resources" statement. Therefore the file will be closed regardless of whether an exception occurs or not. The
FileNotFoundExceptionis possible during execution of the
ClassNotFoundExceptionis possible when calling the
readObject. Therefore, a generic catch is provided for both exceptions. The program reads the serialized object using the
readObjectmethod and then displays the contents of the object that is read, i.e., the full name of the person.