Java – Serialization Example

Employee.java

public class Employee implements java.io.Serializable {
   public String name;
   public String address;
   public transient int SSN;
   public int number;

   public void mailCheck() {
      System.out.println("Mailing a check to " + name
                           + " " + address);
   }
}

SerializeDemo.java

import java.io.*;

public class SerializeDemo {
   public static void main(String [] args) {
      Employee e = new Employee();
      e.name = "Prasanna Sherekar";
      e.address = "Amravati, Maharashtra, India";
      e.SSN = 11122333;
      e.number = 101;
      try {
         FileOutputStream fileOut = new FileOutputStream("employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
          fileOut.close();
      } catch(IOException i) {
          i.printStackTrace();
      }
   }
}

Java Serialization – Write Object to File

Address.java

import java.io.Serializable;

public class Address implements Serializable {

String street;
String country;

public void setStreet(String street) {
this.street = street;
}

public void setCountry(String country) {
this.country = country;
}

public String getStreet() {
return this.street;
}

public String getCountry() {
return this.country;
}

@Override
public String toString() {
return new StringBuffer(" Street : ")
.append(this.street)
.append(" Country : ")
.append(this.country).toString();
}

}

Serializer.java

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Serializer {

public static void main (String args[]) {

Serializer serializer = new Serializer();
serializer.serializeAddress("wall street", "united state");
}

public void serializeAddress(String street, String country) {

Address address = new Address();
address.setStreet(street);
address.setCountry(country);

try {

FileOutputStream fout = new FileOutputStream("c:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(address);
oos.close();
System.out.println("Done");

} catch(Exception ex) {
ex.printStackTrace();
}
}
}