Answer to Question #253213 in Java | JSP | JSF for Tarurendra Kushwah

Question #253213

Explain serialization and Deserialization using Serializable interface.


1
Expert's answer
2021-10-20T16:39:39-0400
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);
		}


	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS