In this java post, you will learn about java serialization and deserialization with clear examples.
SERIALIZATION & DESERIALIZATION
- Serialization: Process of converting java object into bytes (binary form)
- Process of converting an object’s state (including its reference) to a sequence of bytes
- Serialization is used when we want to persist (store) the object
- Java object serialization is used to persist java object to a file, database, network, process or any other system
- Deserialization: Conversion of byte code to corresponding java objects.
NEED OF SERIALIZATION
- Serialization is usually used when there is need to send user data over network or to store in files
- Here data is object and not text
- Now the problem is our network infrastructure and our hard disk are hardware components that understand bits and bytes and not java objects
- Serialization is the translation of java object’s values / states to bytes to send it over the network or to save it.
SERIALIZABLE INTERFACE / EMPTY / MARKER INTERFACE
- In serialization process, current class must implement the Serializable interface (marker / empty interface) else the serialization process will fail
- If interface contains no fields or methods then it is called empty or marker or Serializable interface
- Package: java.io.Serializable;
GUIDELINES USED IN SERIALIZATION
- If they any members in a Serializable class, then the following guidelines apply:
- If they are primitives or basic types (e.g.: int, float) they are automatically Serializable
- If they are non-primitive objects, they must implement a Serializable interface.
CHARACTERISTICS
- Process of saving an object in a storage medium (like a file or a memory buffer) or to transmit it over a network converting in binary form
- The serialized objects are JVM independent & can be re-serialized by any JVM
- Java object states are converted into a byte stream. This type of the file can not be understood by the user. It is a special type of object. (i.e. reused by the JVM) This process is also called Deflating / Marshaling an Object).
CLASSES AND METHODS
ObjectOutputStream and ObjectInputStream
- These are high level streams that contains the methods for serializing and deserializing an object
- These high level streams are each chained to a low level stream such as FileInputStream and FileOutputStream. Because the low level streams handle the Bytes of Data
1. ObjectOutputStream
- This is a predefined class used only for serializing objects
- Package: java.io.*;
2. ObjectInputStream
- This is a predefined class used only for deserializing objects
- Package: java.io.*;
IMPORTANT METHODS
- ObjectOutputStream has many methods for serializing object but commonly used method is
- void writeObject(Object)
- It serializes an object(save the state of the class) and sends it to the output stream
- It is used only in SERIALIZATION process
- It takes only one argument
- Return Type: void
- Object readObject()
- It is used to deserialize the object from ObjectInputStream
- It is used only in DESERIALIZATION process
- It takes no argument
- Return Type: Object
EXAMPLE OF SERIALIZATION / MARSHALING AN OBJECT
STEPS
- Implementation class
- Implement Serializable interface
- Define the logic
- Conversion class
- Convert the java object to bytes
1. SOURCE CODE
(Student.java)
import java.io.*;
// current class should implement predefined Serializable interface
public class Student implements Serializable
{
String sname;
int age;
String dept;
String clg;
transient String np; // it won’t be serialized bcoz it was declared using transient keyword
public Student(String n, int a, String d, String c, String p)
{
sname=n;
age=a;
dept=d;
clg=c;
np=p;
}
}
(JSerialResult.java)
import java.io.*;
public class JSerialResult {
String fp=”pugazh.txt”; // current directory
FileOutputStream fs;
ObjectOutputStream os;
DataInputStream ds=new DataInputStream(System.in);
public void convertJavaObject2Bytes()throws Exception
{
// create object for container class
Student ss=new Student(“Srivatsan”,20,”IT”,”MIT-AU”,”Chennai”);
File f=new File(fp);
try
{
fs=new FileOutputStream(f);
os=new ObjectOutputStream(fs);
// store or write java object to bytes
os.writeObject(ss);
System.out.println(“Serialization is done successfully!\nJava Object is successfully converted to Bytes”);
System.out.println(“Converted File is Stored at “+f.getAbsolutePath());
System.out.println(“Do u want to view the File Contents(Bytes): Press Yes / No :”);
String uc=ds.readLine();
if(uc.equalsIgnoreCase(“Yes”)==true)
{
dispFileContents(fp);
}
}
catch(Exception ex)
{
// no code
}
}
public void dispFileContents(String fp)throws Exception
{
FileReader fr=new FileReader(new File(fp));
BufferedReader br=new BufferedReader(fr);
String rs;
System.out.println(“File Contents in Bytes:”);
while((rs=br.readLine())!=null)
{
System.out.println(rs);
}
}
public static void main(String[] args)throws Exception
{
System.out.println(“———————————-“);
System.out.println(“\tSerialization:Conversion of Object to Bytes”);
System.out.println(“———————————-“);
JSerialResult obj=new JSerialResult();
obj.convertJavaObject2Bytes();
}
}
2. OUTPUT
2.1 CONVERTED FILE VERIFICATION
2.2 RESULT IN NETBEANS TERMINAL
II. EXAMPLE OF DESERIALIZATION
1. SOURCE CODE
(JDeserialResult.java)
import java.io.*;
public class JDeserialResult {
String fp=”pugazh.txt”;
File f=new File(fp);
public void convertBytes2JavaObject()throws Exception
{
if(f.exists())
{
FileInputStream fin=new FileInputStream(f);
ObjectInputStream os=new ObjectInputStream(fin);
// De-Marshaling an object from ObjectInputStream
Student sobj=(Student)os.readObject();
System.out.println(“Student Details:”);
System.out.println(“Name \t\t: “+sobj.sname);
System.out.println(“Age \t\t: “+sobj.age);
System.out.println(“Dept \t\t: “+sobj.dept);
System.out.println(“College \t: “+sobj.clg);
}
else
{
System.out.println(“Sorry,File is missing or File may be in different path\nPlease use valid File path”);
}
}
public static void main(String[] args)throws Exception
{
System.out.println(“——————————-“);
System.out.println(“\tDeserialization: Conversion of Bytes to Object”);
System.out.println(“——————————-“);
JDeserialResult obj=new JDeserialResult();
obj.convertBytes2JavaObject();
System.out.println(“——————————-“);
}
}
2. OUTPUT
More Useful Tutorials
-
How to convert Word to Number in Bash Script
FacebookTweetPinLinkedInEmailShares0SharePrint In this bash tutorial, you will get convert word to number in bash script with examples.This is implemented using for loop, tr command, switch case in shell…
-
How to Count Word Frequency in Bash Script
FacebookTweetPinLinkedInEmailShares0SharePrint In this bash tutorial, you will get the program about how to count word frequency in bash script. This is done by using for loop,…
-
Bash Script – How to convert Number to Words
FacebookTweetPinLinkedInEmailShares0SharePrint In this tutorial, you will see how to convert numbers to words using bash script. This shell script can be done with the help of switch case…