Serialization is converting the data or object’s state into a series of bytes that can be converted back to the data at any point. The serialized data can be transmitted and
The above illustration gives a concept of serialization of a file where a Sender sends a file in a serialized form, and the Receiver gets it, and by deserializing, it can get the content from that file.
For instance, you and your friend are collaborating on a project, and you want to talk to them about it. Unfortunately, they are somewhere else, so you send them an email outlining your project to let them know how your work is coming along.
You turned the ideas into a serialized email that your friend could send, save, render, and then read. The de-serialization process begins after reading this email and creating an internal mental model of the concept so one can process it.
In the coding widget below, a Java program gives the implementation of the Serialization of an object.
import java.io.*;//Declare a Serialized classpublic class Serialized {public static void display(Sender obj){System.out.println("Name = " + obj.name + "\nMessage = " + obj.Message);}//Implement Serializationpublic static void serlize(String filename,Sender data[]){try {FileOutputStream file = new FileOutputStream(filename);ObjectOutputStream out = new ObjectOutputStream(file);out.writeObject(data);out.close();file.close();System.out.println("Serialized successfully\n");}// To catch errorscatch(Exception err){System.out.println(err);}data = null;}//Implement De serializationpublic static void deSerialize(String filename,Sender data[]){try {FileInputStream file = new FileInputStream(filename);ObjectInputStream in = new ObjectInputStream(file);data = (Sender[])in.readObject();in.close();file.close();System.out.println("deserialized Successfully\n");System.out.println("Data after deserializing \n");}catch(Exception err){System.out.println(err);}}public static void main(String[] args){ //Created a Sender class objectSender data[] = new Sender[2];data[0]= new Sender();data[0].name="Sender :";data[0].Message="Hi! This is a message from sender";String filename = "educative.txt";serlize(filename,data);// Start DeserializingdeSerialize(filename,data);display(data[0]);}}
Line 5: We declare a Sender
class in which we declare variables to store the Sender message.
In the Serialized file,
Lines 10-25: We declare a Serialize
function in which we serialize the enrollment data, and then we use the catch
function to catch the occurred errors
Lines 28-40: We declare a deSerialize
function in which we de-serialize the Sender data, and then we use the catch
function to catch the occurred errors
Lines 43-61: We declare an object of Sender with the name of data
and then pass the enrollment data to it, and after that, we call the serlize
function to serialize the data, and then we call the deSerialize
function to de-Serialize data.
Free Resources