How do you read an object from a file in Java?

Java MCQ: How do you read an object from a file in Java?

a) readObject()
b) loadObject()
c) deserializeObject()
d) restoreObject()

Answer:

a) readObject()

Explanation:

The readObject() method in Java is used to read an object from a file, enabling the process of deserialization. Deserialization is the reverse process of serialization, where a byte stream is converted back into an object. The readObject() method is part of the ObjectInputStream class, which is used in conjunction with a FileInputStream to read the serialized object from a file.

Here’s an example of how to deserialize and read an object from a file:

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

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

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

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.");
            System.out.println("Name: " + person.name);
            System.out.println("Age: " + person.age);
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("An error occurred during deserialization.");
            e.printStackTrace();
        }
    }
}

In this example, the readObject() method is used to read an instance of Person from the file person.dat. The object is deserialized from the byte stream and restored to its original state. The deserialized object’s properties are then printed to the console.

Deserialization is commonly used when you need to retrieve the state of an object that was previously serialized and saved to a file. The readObject() method is crucial for reconstructing objects from stored data, making it a key tool in Java’s file handling capabilities.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top