Explain serialization and Deserialization using Serializable interface.
import java.io.*;
class MyClass implements java.io.Serializable{
public int id;
public String name;
public MyClass(int i, String n){
id = i;
name = n;
}
}
class Main
{
public static void main(String[] args)
{
MyClass ob = new MyClass(123, "abc");
String f-nae = "file.ser";
// Serialization
try
{
FileOutputStream f1 = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(ob);
out.close();
f1.close();
System.out.println("Object has been serialized");
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
MyClass object1 = null;
// Deserialization
try
{
FileInputStream f1 = new FileInputStream(f-nae);
ObjectInputStream in = new ObjectInputStream(f1);
object1 = (MyClass)in.readObject();
in.close();
f1.close();
System.out.println("Deserialization has happened ");
System.out.println("id = " + object1.id);
System.out.println("name = " + object1.name);
}
catch(IOException ex)
{
System.out.println(ex);
}
catch(ClassNotFoundException ex)
{
System.out.println(ex);
}
}
}
Comments
Leave a comment