In an earlier article, we looked at how to write an object to a file using Java. In this short article, you'll learn how to read a Java Object from a file or how to deserialize the serialized object saved in a file.

The deserialization process is quite similar to the serialization process. Basically, to read an object from a file, you need to follow the below steps:

  • Open the file that has the Java Object stored using FileInputStream.
  • Create an instance of ObjectInputStream and pass FileInputStream as an argument to its constructor.
  • Use ObjectInputStream.readObject() method to read the object from the file.
  • The above method will return a generic object of type Object. You need to cast this object to its original type to properly use it.

Create Java Class

Here is how our User.java class looks like that we used to write an object to a file in the previous article:

public class User implements Serializable {

    public String name;
    public String email;
    private String[] roles;
    private boolean admin;

    public User() {
    }

    public User(String name, String email, String[] roles, boolean admin) {
        this.name = name;
        this.email = email;
        this.roles = roles;
        this.admin = admin;
    }

    // getters and setters, toString() .... (omitted for brevity)
}

Read Object from File

The following example shows how you can deserialize the object.dat file and convert it back to a User object in Java 7 or higher:

try (FileInputStream fis = new FileInputStream("object.dat");
     ObjectInputStream ois = new ObjectInputStream(fis)) {

    // read object from file
    User user = (User) ois.readObject();

    // print object
    System.out.println(user);

} catch (IOException | ClassNotFoundException ex) {
    ex.printStackTrace();
}

The above code will print the following on the console:

User{name='John Doe', email='john.doe@example.com', roles=[Member, Admin], admin=true}

If you are using an older Java version (Java 6 or below), you have to manually close ObjectInputStream as shown below:

try {
    FileInputStream fis = new FileInputStream("object.dat");
    ObjectInputStream ois = new ObjectInputStream(fis);

    // read object from file
    User user = (User) ois.readObject();

    // print object
    System.out.println(user);
    
    // close reader
    ois.close();

} catch (IOException | ClassNotFoundException ex) {
    ex.printStackTrace();
}

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.