Read Object From File in Java

Reading objects from a file in Java is typically done using Object Input/Output Streams. The ObjectInputStream class allows for deserialization, i.e., converting a sequence of bytes back into an object. 

Before proceeding, make sure the class you want to deserialize implements the Serializable interface. This interface is a marker interface, signaling to the JVM that the class can be serialized or deserialized. 

Here's a step-by-step guide:

Making the Class Serializable 

First, the class you wish to serialize and deserialize should implement the Serializable interface. Let's first create the Employee class and which implements the 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;
     }
}

Read Object from File

Let's create employees.txt file under some directory. Next, let's write a code to read file and covert into Employee object:
/**
 * 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
In the code above: 
A FileInputStream is used to read bytes from a file. 

The ObjectInputStream reads the bytes and deserializes them back into an object. 

We use the readObject method of ObjectInputStream to deserialize the object. This method returns an Object, so we need to cast it back to the original Employee type. 

Exception handling is essential because many things can go wrong, e.g., the file might not exist, the class structure might have changed, etc.

Comments