Advertisement
Methods | Description |
---|---|
writeObject() | This method of ObjectOutputStream class writes the state of an object to the stream, so that it can be saved within a file, and thus performing serialization. |
readObject() | This method of ObjectInputStream class reads the saved object from a file in which the object's state was saved, and thus performing deserialization. |
Advertisement
//Java - Example of Serialization and Deserialization
import java.io.*;
//A class implementing Serializable interface
class Serialz implements Serializable
{
int i=0;
public static void main(String... ar)
{
Serialz ob= new Serialz();
ob.i=10; //object instance variable's value set to 10
System.out.println("Before Serialization object has value : " + ob.i);
try
{
FileOutputStream fos= new FileOutputStream("E:\\File.ser");//Saved state of the object is written to this file
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(ob); //Serializing, i.e. saving the state of this object, ob
oos.close();
}
catch(Exception exp)
{
System.out.println(exp);
}
try
{
FileInputStream fis= new FileInputStream("E:\\File.ser"); //Reading the same file for Deserialization
ObjectInputStream ois= new ObjectInputStream(fis);
ob = (Serialz)ois.readObject(); //Deserializing, i.e. restoring the object to its original state.
ois.close();
System.out.println("After Deserialization restored object has value : "+ ob.i);
}
catch(Exception exp )
{
System.out.println(exp);
}
} //main method ends
} //class definition ends
Before Serialization object has value : 10
After Deserialization restored object has value : 10
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement