How to Read Object from File

1. Overview

In this example, we will use ObjectInputStream class to read employee object to file.
The deserialization process is quite similar with the serialization, you need to use ObjectInputStream to read the content of the file and convert it back to a Java object.
We can also read String, Arrays, Integer, and Date from a file using ObjectInputStream class because these classes internally implement the java.io.Serializable interface.

2. Read Object from File Example

  1. Let's first create Employee class and which implements the java.io.Serializable interface.
class Employee implements Serializable {
 private static final long serialVersionUID = 1L;
 private int id;
 private String name;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}
Let'employees.txt file under some directory write employee object into a file using ObjectOutputStream class.
/**
 * This Java program demonstrates how to read object from file.
 * @author javaguides.net
 */

public class ObjectInputStreamExample {
 public static void main(String[] args) {
  try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("employees.txt"))) {
   final Employee employee = (Employee) in.readObject();
   System.out.println(" printing employee object details");
   System.out.println(employee.getId() + " " + employee.getName());
   System.out.println(" printing address object details");
  } catch (IOException | ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}
Output:
printing employee object details
100 ramesh
printing address object details

3. Reference

Comments