There are few important things that need to be known.
- In Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable.
- You can also prevent some data in your object from being serialized by marking the attribute as transient.
- It is important to notice that what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized.
import java.io.*;
public class Student implements Serializable {
public String name;
public String address;
public transient int regNumber;
public int classNumber;
public Student(String name,String add,int regNo,int clsNo){
this.name=name;
this.address=add;
this.regNumber=regNo;
this.classNumber=clsNo;
}
public void introduce(){
System.out.println("Hi!! This is "+name+" and he is from "+address);
}
public String toString(){
return name+" - "+address+" - "+regNumber+" - "+classNumber;
}
}
Here is a example of how to serialize an object and save in a file
import java.io.*;
public class Serializer {
public static void main(String args[]){
Student stdnt = new Student("Jhon","111 street,george town",1234,8);
try{
String path = "/home/iiii/store/student.ser";
FileOutputStream fo = new FileOutputStream(path);
ObjectOutputStream oo=new ObjectOutputStream(fo);
oo.writeObject(stdnt);
oo.close();
fo.close();
System.out.println("Object is serialized and saved in "+path);
}catch(IOException e){
e.printStackTrace();
}
}
}
Here is a example of how to deserialize what is saved in the file in to an object.
import java.io.*;
public class Deserializer {
public static void main(String args[]){
String path = "/home/iiii/store/student.ser";
Student s = null;
try{
FileInputStream fi = new FileInputStream(path);
ObjectInputStream oi = new ObjectInputStream(fi);
s=(Student) oi.readObject();
oi.close();
fi.close();
}catch(IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(s);
}
}
No comments:
Post a Comment