How to Read an Object from a File in Java

Reading an object from a file in Java is a common task that involves deserializing the object. Serialization is the process of converting an object into a byte stream, and deserialization is the reverse process of converting the byte stream back into an object. This blog post will guide you through the process of reading an object from a file using the ObjectInputStream class.

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Writing an Object to a File
  4. Reading an Object from a File
  5. Complete Example
  6. Conclusion

Introduction

Java provides a simple and efficient way to read objects from a file using the ObjectInputStream class. This class is part of the java.io package and is used to read primitive data types, objects, and arrays of objects from an input stream.

Prerequisites

Before you can read an object from a file, you need to ensure that the object class implements the Serializable interface. This interface is a marker interface, meaning it does not contain any methods, but it tells the Java Virtual Machine (JVM) that the class can be serialized and deserialized.

Example

import java.io.Serializable;

public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

Writing an Object to a File

Before reading an object from a file, we need to write the object to the file. This can be done using the ObjectOutputStream class.

Example

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class WriteObjectToFile {
    public static void main(String[] args) {
        Person person = new Person("John Doe", 30);

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"))) {
            oos.writeObject(person);
            System.out.println("Object has been serialized and written to person.dat");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • A Person object is created and initialized.
  • An ObjectOutputStream is created to write the object to a file named person.dat.
  • The writeObject method is called to serialize the object and write it to the file.
  • The try-with-resources statement ensures that the stream is closed automatically.

Reading an Object from a File

To read an object from a file, you need to use the ObjectInputStream class. This class deserializes objects previously written using an ObjectOutputStream.

Example

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ReadObjectFromFile {
    public static void main(String[] args) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"))) {
            Person person = (Person) ois.readObject();
            System.out.println("Object has been deserialized: " + person);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • An ObjectInputStream is created to read the object from a file named person.dat.
  • The readObject method is called to deserialize the object from the file.
  • The object is cast to the Person class and printed to the console.
  • The try-with-resources statement ensures that the stream is closed automatically.

Complete Example

Combining both writing and reading operations, here is a complete example:

Person.java

import java.io.Serializable;

public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

WriteObjectToFile.java

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class WriteObjectToFile {
    public static void main(String[] args) {
        Person person = new Person("John Doe", 30);

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"))) {
            oos.writeObject(person);
            System.out.println("Object has been serialized and written to person.dat");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ReadObjectFromFile.java

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ReadObjectFromFile {
    public static void main(String[] args) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"))) {
            Person person = (Person) ois.readObject();
            System.out.println("Object has been deserialized: " + person);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Conclusion

Reading an object from a file in Java involves deserializing the object using the ObjectInputStream class. This process is straightforward and requires the object class to implement the Serializable interface. By following the steps outlined in this tutorial, you can efficiently serialize and deserialize objects in your Java applications.

Feel free to experiment with the code examples provided in this tutorial to gain a deeper understanding of how to read objects from files in Java. Happy coding!

Comments