Home » Core Java » io » File » How to Read an Object from File in Java

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services, currently the technical lead in a in-house PCRF solution. Particularly interested in multi-tier architecture, middleware services and mobile development (contact). Ilias Tsagklis is co-founder and Executive Editor at Java Code Geeks.

How to Read an Object from File in Java

In the previous tutorial we saw how to write an Object to a file in Java. In this example we are going to see how to read an Object from the file that we’ve stored it earlier.

Basically, to read an Object from a file, one should follow these steps:

  • Open a FileInputStream to the file that you’ve stored the Object to.
  • Open a ObjectInputStream to the above FileInpoutStream.
  • Use readObject method of ObjectInputStream class to read the Object from the file.
  • The above method returns an Object of type Object. So you have to cast it to the original type to use it properly.

Let’s see the code snippets that follow:
Student.java

package com.javacodegeeks.java.core;

import java.io.Serializable;

public class Student implements Serializable {

	//default serialVersion id
	private static final long serialVersionUID = 1L;

	private String first_name;
	private String last_name;
	private int age;

	public Student(String fname, String lname, int age){
		this.first_name = fname;
		this.last_name  = lname;
		this.age        = age;
	}

	public void setFirstName(String fname) {
		this.first_name = fname;
	}

	public String getFirstName() {
		return this.first_name;
	}

	public void setLastName(String lname) {
		this.first_name = lname;
	}

	public String getLastName() {
		return this.last_name;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getAge() {
		return this.age;
	}

	@Override
	public String toString() {
		return new StringBuffer(" First Name : ").append(this.first_name)
				.append(", Last Name : ").append(this.last_name).append(", Age : ").append(this.age).toString();
	}

}

ObjectIOExample.java

package com.javacodegeeks.java.core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectIOExample {

	private static final String filepath="C:\\Users\\nikos7\\Desktop\\obj";

	public static void main(String args[]) {

		ObjectIOExample objectIO = new ObjectIOExample();

		//Read object from file
		Student st = (Student) objectIO.ReadObjectFromFile(filepath);
		System.out.println(st);
	}

	public Object ReadObjectFromFile(String filepath) {

		try {

			FileInputStream fileIn = new FileInputStream(filepath);
			ObjectInputStream objectIn = new ObjectInputStream(fileIn);

			Object obj = objectIn.readObject();

			System.out.println("The Object has been read from the file");
			objectIn.close();
			return obj;

		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
}

Output

The Object has been read from the file
 First Name : John, Last Name : Frost, Age : 22

Here is the code of the complete Read/Write Object From/To File interface in Java:

Student.java

package com.javacodegeeks.java.core;

import java.io.Serializable;

public class Student implements Serializable {

	//default serialVersion id
	private static final long serialVersionUID = 1L;

	private String first_name;
	private String last_name;
	private int age;

	public Student(String fname, String lname, int age){
		this.first_name = fname;
		this.last_name  = lname;
		this.age        = age;
	}

	public void setFirstName(String fname) {
		this.first_name = fname;
	}

	public String getFirstName() {
		return this.first_name;
	}

	public void setLastName(String lname) {
		this.first_name = lname;
	}

	public String getLastName() {
		return this.last_name;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getAge() {
		return this.age;
	}

	@Override
	public String toString() {
		return new StringBuffer(" First Name : ").append(this.first_name)
				.append(", Last Name : ").append(this.last_name).append(", Age : ").append(this.age).toString();
	}

}

ObjectIOExample.java

package com.javacodegeeks.java.core;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectIOExample {

	private static final String filepath="C:\\Users\\nikos7\\Desktop\\obj";

	public static void main(String args[]) {

		ObjectIOExample objectIO = new ObjectIOExample();

		Student student = new Student("John","Frost",22);
		objectIO.WriteObjectToFile(filepath, student);

		//Read object from file
		Student st = (Student) objectIO.ReadObjectFromFile(filepath);
		System.out.println(st);
	}

	public void WriteObjectToFile(String filepath,Object serObj) {

		try {

			FileOutputStream fileOut = new FileOutputStream(filepath);
			ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
			objectOut.writeObject(serObj);
			objectOut.close();
			System.out.println("The Object  was succesfully written to a file");

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public Object ReadObjectFromFile(String filepath) {

		try {

			FileInputStream fileIn = new FileInputStream(filepath);
			ObjectInputStream objectIn = new ObjectInputStream(fileIn);

			Object obj = objectIn.readObject();

			System.out.println("The Object has been read from the file");
			objectIn.close();
			return obj;

		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
}

Output

The Object  was succesfully written to a file
The Object has been read from the file
 First Name : John, Last Name : Frost, Age : 22

 
This was an example on how to Read an Object from File in Java

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close