+92 332 4229 857 99ProjectIdeas@Gmail.com

How to write a object in file (Serialization) (Java)



How to write a object in file (Serialization) (Java):

  -> Sending an object to a stream, to some file or somewhere on network.
  -> Object know how to read/write themselves to streams.

Serialization is also called as flattening, Streaming, Dehydrate (rehydrate = read), Archiving.

Serializable Interface:

              By implementing this interface a class declares that is willing to  be read/written by automatic serializable machinery. import java.io.*; for using serialization.

 Automatic Writing:
     System knows how to recursively write out the state of an object to stream.
     Recursively follows references and writes out those objects too!

 Automatic Reading: 
     System knows how to read the data from Stream and re-create object in memory
     Downcasting is required

Code
 
Creating an Employee class which contains id, name , default and parameterized constructor and one method print(). To serialize an object class have to implement Serializable interface.

import java.io.*;

public class Employee implements Serializable {

    private int id;
             
    private String name;
       
  // Default Constructor
     public Employee() {
             
              this.id = 0;
              this.name = "Anonymous";
    }
      
  // Parametrized Constructor
    public Employee(int i , String n) {
             
              this.id = i;
              this.name = n;
    }
  
    public void print() {
             
              System.out.println("Id Is : " + this.id +
                                  "\n Name Is : " + this.name );
   }
}

DRIVER CLASS FOR EXECUTING PROGRAM:

public class Driver {

  public static void main(String[] args) {
      
      try {
              
SERIALIZING A SINGLE OBJECT:
 
Creating an Employee class object:
         
        Employee emp = new Employee(1, "osama");

For writing aan object to file create FileOutputStream object and pass the path of file as argument:
        
        FileOutputStream fos = new FileOutputStream("D:\\a.ser");
        
Now, create ObjectOutputStream object and in its constructor pass FileOutputStream object as argument:
         
        ObjectOutputStream oos = new ObjectOutputStream(fos);
  
.writeObject() is the method ObjectOutputStream class which takes one argument the object that is to be serialized, here that object is of Employee class:

       oos.writeObject(emp);
             
 
       } catch (Exception e) {

             e.printStackTrace();
       }
     
}      

SERIALIZING THE WHOLE ARRAYLIST OF EMPLOYEE OBJECTS:


import java.io.*;
import java.util.*;

public class Driver {

  public static void main(String[] args) {
      
       try {
             
           
Creating ArrayList which can hold Employee class objects:
        
          ArrayList<Employee> listEmployee = new ArrayList<Employee>();


Adding Employee objects in ArrayList:

          listEmployee.add(new Employee(1, "osama"));
          listEmployee.add(new Employee(2, "saad"));
          listEmployee.add(new Employee(3, "bilal"));
          listEmployee.add(new Employee(4, "shizzi"));
          listEmployee.add(new Employee(5, "hamza"));

For writing an object to file create FileOutputStream object and pass the path of file as argument:

          FileOutputStream fos = new FileOutputStream("D:\\a.ser");

Now, create ObjectOutputStream object and in its constructor pass FileOutputStream object as argument:
 
          ObjectOutputStream oos = new ObjectOutputStream(fos);

Here, writing / serializing a ArrayList object to file, in this way you can do it or the other way is, you can run loop and add the Employee objects in file one by one:

          oos.writeObject(listEmployee);


          } catch (Exception e) {

               e.printStackTrace();
         }
           
    }                   
}
 
WRITING OBJECTS IN FILE ONE BY ONE:


    for (int i = 0 ; i < listEmployee.size() ; i++) {
              
Getting each object from listEmployee and cast to Employee:

           Employee emp = (Employee)listEmployee.get(i);

And write the object in file:
           oos.writeObject(emp);
    }

0 comments: