ObjectInputStream in Java can be used to convert InputStream to object. The process of converting the input stream to an object is called deserialization. In last post, we learned about ObjectOutputStream and converted java object to output stream and write to file. Here we will read the same serialized file to create an object in java.
Table of Contents
ObjectInputStream
ObjectInputStream is part of Java IO classes. It’s purpose is to provide us a way to convert input stream to object in java program. ObjectInputStream constructor take InputStream as argument. Since we are reading serialized object from file, we will be using FileInputStream with our ObjectInputStream to read object from file.
Java ObjectInputStream Example
java.io.ObjectInputStream
readObject()
is used to read input stream to Object. We have to do class casting to convert Object to actual class. Below is the ObjectInputStream example program to read object from file.
package com.journaldev.files;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ObjectInputStreamExample {
public static void main(String[] args) {
try {
FileInputStream is = new FileInputStream("EmployeeObject.ser");
ObjectInputStream ois = new ObjectInputStream(is);
Employee emp = (Employee) ois.readObject();
ois.close();
is.close();
System.out.println(emp.toString());
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
}
Below image shows the output produced by the above program.
There is a lot more to serialization and deserialization in java. For example, what happens if we change the java class before deserialization. What is the use of serialVersionUID
? What happens to serialization with inheritance where superclass doesn’t implement the Serializable interface? I have tried to answer these into a detailed post, please read Serialization in java.
Reference: API Doc