How to read object from a file in java

In this post, we will see how to read object from file in java. In last post, we have already seen how to write object to a file and created employee.ser , now in this post, we are going to read same file and retrieve back Employee object.

Reading object from file using ObjectInputStream may be referred as Deserialization.

Steos for reading object from file are:

Lets take an example:
Create same as last example in src->org.arpit.java2blog
package org.arpit.java2blog;
public class Employee implements Serializable{ 
   private static final long serialVersionUID = 1L;    
  int employeeId;
    String employeeName;
    String department;
    public int getEmployeeId() {
        return employeeId;
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    public String getEmployeeName() {
        return employeeName;
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    public String getDepartment() {
        return department;
    public void setDepartment(String department) {
        this.department = department;

Create in src->org.arpit.java2blog
package org.arpit.java2blog;

public class DeserializeMain {
  * @author Arpit Mandliya
 public static void main(String[] args) {
  Employee emp = null;
          FileInputStream fileIn =new FileInputStream("employee.ser");
          ObjectInputStream in = new ObjectInputStream(fileIn);
          emp = (Employee) in.readObject();
       }catch(IOException i)
       }catch(ClassNotFoundException c)
          System.out.println("Employee class not found");
       System.out.println("Deserialized Employee...");
       System.out.println("Emp id: " + emp.getEmployeeId());
       System.out.println("Name: " + emp.getEmployeeName());
       System.out.println("Department: " + emp.getDepartment());

3.Run it:

When you run above and you will get following output:
Deserialized Employee...
Emp id: 101
Name: Arpit
Department: CS

These are some simple steps to read object from file. If you want to go through some complex scenario you can go through Serialization in java

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012