Java Serialization Vs De-Serialization
- The capability of an object to exist beyond the execution of the program that created it is known as persistence
- To make the file object persistent, the file object has to be saved, saving the file object is called serialization
- JDK 1.2 provides the Serializable interface in the java.iopackage to support object serialization
- The readObject() method of the ObjectInputStreamclass is used to read objects from the stream
- The writeObject() method of the ObjectOutputStream class writes objects to a stream
Example 1
import java.io.*;
class StringSerializeExample
{
public static void main(String arg[]) throws Exception
{
String str;
System.out.println(“Enter the String”);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
str= br.readLine();
FileOutputStream output = new FileOutputStream(“file1.txt”);
ObjectOutputStream obj = new ObjectOutputStream(output);
obj.writeObject(str); //Serialization
obj.close();
FileInputStream input = new FileInputStream(“file1.txt”);
ObjectInputStream obj1 = new ObjectInputStream(input);
String str1 = null;
str1=(String)obj1.readObject(); //de-serialization
System.out.println(“The String is : ” +str1);
}
}
Example 2
import java.io.*;
class Emp implements Serializable
{
int eid;
String ename;
transient String eadd;
Emp(int id, String name, String add)
{
eid = id;
ename = name;
eadd = add;
}
void disp()
{
System.out.println(+eid + "" +ename + "" +eadd);
}
}
public class EmpSerialize
{
public static void main(String arg[]) throws Exception
{
Emp e = new Emp(01 ,"Tom" ,"india");
FileOutputStream f = new FileOutputStream("Employee.txt");
ObjectOutputStream obj = new ObjectOutputStream(f);
obj.writeObject(e);
FileInputStream f1 = new FileInputStream("Employee.txt");
ObjectInputStream obj1 = new ObjectInputStream(f1);
Emp e1 = null;
e1=(Emp) obj1.readObject();
System.out.println("The employee details is:");
e1.disp();
}
}
Recent Comments