How do you write an object to a file in Java?

Java MCQ: How do you write an object to a file in Java?

a) writeObject()
b) saveObject()
c) serializeObject()
d) storeObject()

Answer:

a) writeObject()

Explanation:

The writeObject() method in Java is used to write an object to a file, enabling the process of serialization. Serialization is the process of converting an object into a byte stream so that it can be easily saved to a file or transmitted over a network. The writeObject() method is part of the ObjectOutputStream class, which is used in conjunction with a FileOutputStream to write the serialized object to a file.

Here’s an example of how to serialize and write an object to a file:

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

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 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 file.");
        } catch (IOException e) {
            System.out.println("An error occurred during serialization.");
            e.printStackTrace();
        }
    }
}

In this example, a Person class implements the Serializable interface, making it serializable. The writeObject() method is used to write an instance of Person to the file person.dat. The object is converted into a byte stream and saved to the file.

Serialization is particularly useful when you need to persist the state of an object to a file or transmit the object over a network. The writeObject() method is a key part of this process, allowing complex objects to be easily stored and retrieved.

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