Thursday 18 October 2012

Serialization Example(Read and Write)

//Example to Serialize an address.

//Example of Serialization
package com.corejava.gaurav.examples;
import java.io.Serializable;

public class Address4Serialization implements Serializable{
   
     /**
     *
     */
    private static final long serialVersionUID = 7488167097372042706L;
    private String city;
    private String colony;
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getColony() {
        return colony;
    }
    public void setColony(String colony) {
        this.colony = colony;
    }
   
    @Override
    public String toString(){
        return new StringBuilder(" Colony: ").append(this.colony).append(" City:--").append(this.city).toString();
    }

}
 
 //Writing the Address in the address4serialization.ser file
 
package com.corejava.gaurav.examples;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;


public class AddressSerializableClass4Write {
  
    public static void main(String args[]){
      
        Address4Serialization add = new Address4Serialization();
        add.setColony("Hitech City");
        add.setCity("Hyderabad");
        try{
        FileOutputStream fos = new FileOutputStream("C:\\address4serialization.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(add);
        System.out.println("address4serialization.ser is created*");
        oos.close();
        System.out.println("File Serialization Completed-");
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
}


//Reading the persist file(address4serialization.ser) from file system
 
package com.corejava.gaurav.examples;
import java.io.FileInputStream;
import java.io.ObjectInputStream;


public class AddressSerializableClass4Read {
   
    public static void main(String args[]){
        Address4Serialization address;
       
        try{
            FileInputStream fis = new FileInputStream("C:\\address4serialization.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            address = (Address4Serialization)ois.readObject();
            System.out.println("Colony is-"+address.getColony());
            System.out.println("City is-"+address.getCity());
            ois.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

}

No comments:

Post a Comment