Monday 20 October 2014

Serializing and Deserializing a multiple Object

Serializing and Deserializing  a multiple Object


Make function to write multiple object in to one file

public void writeToBinary (String filename, Object obj, boolean append){
        File file = new File (filename);
        ObjectOutputStream out = null;

        try{
            if (!file.exists () || !append) out = new ObjectOutputStream (new FileOutputStream (filename));
            else out = new AppendableObjectOutputStream (new FileOutputStream (filename, append));
            out.writeObject(obj);
            out.flush ();
        }catch (Exception e){
            e.printStackTrace ();
        }finally{
            try{
                if (out != null) out.close ();
            }catch (Exception e){
                e.printStackTrace ();
            }
        }
    }

Class For Serialiable appending



private  class AppendableObjectOutputStream extends ObjectOutputStream {

        public AppendableObjectOutputStream(OutputStream out) throws IOException {

          super(out);

        }



        @Override

        protected void writeStreamHeader() throws IOException {}

  }



So now we are Serializing multiple object in to the file


public void Serlize() {
EmployeeInfo e = new EmployeeInfo();
e.name = "Appu Patel";
e.address = "At Valsad, Gujarat";
EmployeeInfo e1 = new EmployeeInfo();
e1.name = "Alpan";
e1.address = "At Surat, Gujarat";
EmployeeInfo e2 = new EmployeeInfo();
e2.name = "Rumit";
e2.address = "At Kadi,At Ghadhinagar";
EmployeeInfo e3 = new EmployeeInfo();
e3.name = "Prashant";
e3.address = "At Lilapor, Valsad Gujarat";
try {
FileOutputStream fileOut = new FileOutputStream(
"employee.ser");
writeToBinary("employee.ser", e, true);
writeToBinary("employee.ser", e1, true);
writeToBinary("employee.ser", e2, true);
writeToBinary("employee.ser", e3, true);
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.bin");
} catch (IOException i) {
i.printStackTrace();
}
}

Deserializing multiple object from file


public ArrayList<EmployeeInfo> Deserialize() throws ClassNotFoundException {
      try{
       ArrayList<EmployeeInfo> employees=new ArrayList<EmployeeInfo>();
       EmployeeInfo o=null;
       ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.ser"));

         while (true) {
             try {
                  o = (EmployeeInfo) in.readObject();
                  
                  employees.add(o);
                 // Do something with the object
             } catch (EOFException ex) {
                 break;
             }
         }

         in.close();
      
          in.close();
       System.out.println(employees.size());

         return employees;
     // return employees;
      }catch(IOException i){
         i.printStackTrace();
         return null;
      }
}



All the Best

No comments:

Post a Comment