Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to read Object from a File .

Java Code Example — File Handling Programs

ADVERTISEMENT

Java Program to read Object from a File .

Objective

Write a Java program to deserialize (read) an Object from a file.

Algorithm / Approach

  1. Open a FileInputStream connected to the file containing the object data.
  2. Wrap it in an ObjectInputStream.
  3. Read the object using ois.readObject().
  4. Cast the returned generic Object back to the specific Test class.
  5. Call the display() method on the restored object to prove its state was preserved.
  6. Close the streams.
ReadObject.java
import java.io.*;
class ReadObject {
 void readObj() {
  FileInputStream fis= null;
  ObjectInputStream ois=null;
  String file = "Alok.txt";
  try {
   fis = new FileInputStream(file);
   ois = new ObjectInputStream(fis);
   Test t = (Test)ois.readObject();
   t.display();
  }
  catch(Exception e) {
   System.out.print(e);
  }
  finally {
   try{ 
    fis.close();
    ois.close();  
   }
   catch(Exception e) {
    System.out.print(e);
   }
  }
 }
 public static void main(String[] a)
 {
   ReadObject obj = new ReadObject();
   obj.readObj();
 }
}

Expected Output

Name: Alok
Age: 24

Explanation of the Program

  • Deserialization is the reverse process of serialization: it takes a stream of raw bytes and reconstructs the Java object in memory.
  • Because readObject() returns a generic java.lang.Object, you must explicitly downcast it to your specific class (e.g., (Test) ois.readObject()).
  • Notice how the object's data (Name and Age) survived being written to a text file and was perfectly restored into a living object in a completely different program!

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT