Java has classes, A class has properties. These properties with values called object or state of object. Now we want to save this state of object into file or database. With java serialization we can convert object state into data stream and this data stream would be save into file system or database or create object replica into another system.
Java Serialization Covered Two Process -
- Serialization: Convert object state into data stream.
- Deserialization: Convert data stream into object state.
Simple Java Code Example:
import java.io.Serializable;
public class Student implements Serializable{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void print() {
System.out.println("Name:"+name+" Age:"+age);
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
private static void serializeStudent() {
try {
Student stu = new Student("Ravi", 22);
FileOutputStream fos = new FileOutputStream("student.obj");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(stu);
System.out.println("student serialized");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static Student deserializeStudent() {
Student stu = null;
try{
FileInputStream fis = new FileInputStream("student.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
stu = (Student)ois.readObject();
}catch(Exception e){
e.printStackTrace();
}
return stu;
}
public static void main(String[] args) {
Main.serializeStudent();
Main.deserializeStudent().print();
}
}
Comments
Post a Comment