Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

Read a Serialized Object

Problem - How you can read from a persisted object from binary file?

Solution :
java.io.ObjectInputStream reads persist object from a binary file opened with help of java.io.FileInputStream.

:- Employee object is already stored in c:/sunilos/sunilos.ser

Program :

Step 1 - Coding

Create a text file c:/sunilos/TestReadEmployee.java and copy below contents.

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

 * A program to read from persist data file implemented Serializable interface.
public class TestReadEmployee {

    public static void main(String[] args) throws Exception {
        ObjectInputStream in = new ObjectInputStream(new
        Employee emp = (Employee)in.readObject();
        System.out.println("ID: " +emp.getId());
        System.out.println("First Name: " + emp.getFirstName());
        System.out.println("Last Name: " +emp.getLastName());
        System.out.println("Temp Value: "+emp.getTempValue());

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy TestReadEmployee.java into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile TestReadEmployee.java with help of
    • javac TestReadEmployee.java command. Command will create TestReadEmployee.class file in the same folder.
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java TestReadEmployee command.


ID: 1
First Name: Sun
Last Name: Rays
Temp Value: null

<<Previous | Next>>

Mahima Hardia,
Aug 19, 2011, 2:54 AM