writing-and-reading-data-in-file-using-objectoutputstream-and-objectInputstream-in-java-with-examples
admin
Java file operations objectoutputstream vs objectInputstream
Updated: 06/Feb/2025 by Computer Hope
File handling in Java is a crucial aspect of programming, especially when working with object serialization. In this tutorial, we will explore how to write and read data in a file using ObjectOutputStream and ObjectInputStream in Java.
Object serialization in Java is the process of converting an object into a byte stream, which can then be persisted into a file or transferred over a network. Deserialization is the reverse process where the byte stream is converted back into an object.
Below is a Java program demonstrating how to use ObjectOutputStream for writing objects into a file and ObjectInputStream for reading those objects back from the file.
import java.io.*;
import java.util.*;
class Emp implements Serializable {
private int age;
private String name;
private double sal;
public void get() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter age, name, and salary:");
age = kb.nextInt();
name = kb.next();
sal = kb.nextDouble();
}
public void show() {
System.out.println("Age: " + age);
System.out.println("Name: " + name);
System.out.println("Salary: " + sal);
}
}
public class FileExample6 {
public static void main(String args[]) {
try {
// Writing object to file
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:/emp.dat"));
Emp E = new Emp();
E.get();
oos.writeObject(E);
oos.close();
// Reading object from file
ObjectInputStream ios = new ObjectInputStream(new FileInputStream("D:/emp.dat"));
Emp F = (Emp) ios.readObject();
F.show();
ios.close();
} catch (Exception ex) {
System.out.println("Error in writing or reading Object: " + ex.getMessage());
}
}
}
Defining the Class:
Emp class implements Serializable to allow object serialization.age, name, and sal (salary).get() method takes input for these attributes, and show() displays them.Writing an Object to a File:
ObjectOutputStream is used to serialize the object and save it in a file.writeObject(E) method writes the Emp object to the file.Reading an Object from a File:
ObjectInputStream is used to read the serialized object.readObject() method retrieves the object from the file and casts it back to the Emp class.Handling Exceptions:
try-catch block ensures that errors such as IOException and ClassNotFoundException are properly handled.ObjectOutputStream and ObjectInputStream are used to write and read objects in Java.Serializable interface is mandatory for object serialization.
Using ObjectOutputStream and ObjectInputStream in Java makes object storage and retrieval efficient and easy. This method is useful for saving user data, game progress, and other stateful information.