Serialization converts state of an Java Object to a byte stream so that it can be transferred to other JVM over the network and can be reverted back into a copy of the object without losing it’s state and values.
This example shows how to Serialize a Java Object by implementing the Serializable interface.
Employee.java
1 2 3 4 5 6 7 8 9 10 11 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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(); } } } |