In this tutorial you will learn how to Serialize a java class
Serializing Java Objects
Serialization is a process of saving the object state on a file in the local system. So that we can de-serialize( retrieve ) that object with data.rule to Serialize a java object.
To Serialize a java object, it must implements a Serializable interface.
Then create a FileOutputStream object of new file, and pass the references to ObjectOutputStream class and finally call the writeObject() method of ObjectOutputStream class to save the object to the file.
To de serialize the object create a FileInputStream reference variable passing the same file name in which, you have saved. Then create a ObjectInputStream class passing the FileInputStream reference and finally call the readObject() method of ObjectInputStream class to get the object.
You can mark a variable as transient whose state you don't wish to serialize.
StudentBean.java
package net.roseindia.bean; import java.io.Serializable; public class StudentBean implements Serializable { private static int rollNo; private String name; private String course; public StudentBean() { } public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCourse() { return course; } public void setCourse(String course) { this.course = course; } }
ApplicationClaz.java
package net.roseindia.app; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import net.roseindia.bean.StudentBean; public class ApplicationClaz { public static void main(String[] args) { StudentBean bean1 = new StudentBean(); bean1.setRollNo(10); bean1.setName("John"); bean1.setCourse("B.Sc(IT)"); try { String fileName = "serialize.ser"; /* Saving Object to Database */ FileOutputStream fos = new FileOutputStream(fileName); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(bean1); /* Getting Object to Database */ FileInputStream fin = new FileInputStream(fileName); ObjectInputStream oi = new ObjectInputStream(fin); StudentBean studentBean = (StudentBean) oi.readObject(); System.out.println(studentBean.getRollNo()); System.out.println(studentBean.getName()); System.out.println(studentBean.getName()); } catch (Exception e) { e.printStackTrace(); } } }
When you run this application it will display message as shown below:
10 John John |
[ 0 ] Comments