ObjectInputStream in Java – read Object from File

Filed Under: Java

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.

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.

ObjectInputStream in java, ObjectInputStream java read object from file example

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.

You can checkout more Java IO examples from our GitHub Repository.

Reference: API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages