Here is the Example of Serialization and Deserialization
serialVersionUID will be helped to get exact content while deserializing.
import java.io.Serializable; public class Student implements Serializable{ private static final long serialVersionUID = 1L; public transient int age; public String name; public int sall; public Student(int age,String name){ this.age=age; this.name=name; } }
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; public class serialization{ public static void main(String[] args) throws IOException { Student st=new Student(10,"Kaja"); FileOutputStream fout=new FileOutputStream("E:\\input.txt"); ObjectOutputStream os=new ObjectOutputStream(fout); os.writeObject(st); os.flush(); System.out.println("success"); } }
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; public class deserialize { public static void main(String[] args) throws FileNotFoundException, IOException,ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(new FileInputStream("E:\\input.txt")); Student s=(Student)in.readObject(); System.out.println(s.age+" "+s.name); in.close(); } }