by Dinesh Thakur

Java also supports writing and reading objects to stream (such as a file). The process of reading and writing objects in a file is called object serialization. Writing an object to a file is called serializing the object and reading the object back from a file is called deserializing an object. In Java, serialization occurs automatically. Objects can be converted into a sequence of bytes, or serialized, by using the java.io.ObjectOutputStream class and they can be deserialized or converted from bytes into a structured object, by using java.io.ObjectlnputStream class.

import java.io.*;

class Employee implements Serializable
{      
     int empid;
     String ename;
     double salary;  
     Employee(int id,String name,double sal)
     {      
       empid = id;
       ename = name;
       salary = sal;
     }
     void showInformation()
     {
       System.out.println("Empid : " + empid);
       System.out.println("Empid : " + ename);
       System.out.println("Salary : " + salary);
       System.out.println();
     }
}
     
class ObjectIOStreamExample
{
       public static void main(String[] args)
       {          
           Employee empData[] = {new Employee(1,"Dinesh",50000),
                             new Employee(2,"Shubhra",15000),
                             new Employee(3,"Punar",26000) };
           try
           {   
                FileOutputStream fout = new FileOutputStream("std.dat");
                ObjectOutputStream objOut = new ObjectOutputStream(fout);
                for(int i=0; i<empData.length;i++)
                      objOut.writeObject(empData[i]);
                      objOut.close();
           }
           catch(Exception e){e.printStackTrace();}
           try
           {           
              FileInputStream fin = new FileInputStream("std.dat");
              ObjectInputStream objIn = new ObjectInputStream(fin);          
              Employee emp = (Employee) objIn.readObject();
              emp.showInformation();
              emp = (Employee) objIn.readObject();
              emp.showInformation();
              emp = (Employee) objIn.readObject();
              emp.showInformation();            
              objIn.close();
           }
           catch(Exception e){e.printStackTrace();}
        }
}

ObjectIOStream in Java Example