Example & Tutorial understanding programming in easy ways.

What is Serialization and deserialization in java given with example?

Serialization is the process of writing the state of an object to a byte stream.
Serialization of Object

This class is writing an object of Student class to the Student.ser file. We are using FileOutputStream and ObjectOutputStream to write the object to File.
import java.io.*;

class student implements Serializable

{

String name;

int rid;

static String contact;

student(string n, int r, string c)

{

this.name = n;

this.rid = r;

this.contact = c;

}

}

class Test

{

public static void main(String[] args)

{

try

{

student s = new student("Aman", 04, "9898744");

FileOutputStream fos = new FileOutputStream("student.ser");

Objectoutputstream oos = new ObjectOutputStream(fos);

oos.writeObject(s);

oos.close();

fos.close();

}

catch (Exception e)

{ e. printStackTrace(); }

}

}


Deserialization is the process of restoring these objects.

Deserialization of Object

import java.io * ;

class DeserializationTest

{

public static void main(String[] args)

{

student s=null ;

try

{

FileInputStream fis = new FileInputStream("student.ser");

ObjectOutputStream ois = new ObjectOutputStream(fis);

s = (student)ois.readObject();

}

catch (Exception e)

{ e.printStackTrace(); }

System.out.println(s.name);

System.out. println(s.rid);

System.out.println(s.contact);

}

Read More →