Java Program to read Object from a File .
Objective
Write a Java program to deserialize (read) an Object from a file.
Algorithm / Approach
- Open a
FileInputStreamconnected to the file containing the object data. - Wrap it in an
ObjectInputStream. - Read the object using
ois.readObject(). - Cast the returned generic
Objectback to the specificTestclass. - Call the
display()method on the restored object to prove its state was preserved. - 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 genericjava.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)