Java Programming: Serialization
Java Programming: Serialization
Java Programming: Serialization
Java Programming
Digital Assignment – 3
17BIT0294
Chandra Teja. P
Serialization
Java provides a mechanism, called object serialization where an object can be
represented as a sequence of bytes that includes the object's data as well as
information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its
data can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can
be serialized on one platform and deserialized on an entirely different platform.
Ex:
import java.io.*;
public class SerializeDemo {
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
When serializing an object to a file, the standard convention in Java is to give the file
a .ser extension.
Deserialization
The following DeserializeDemo program deserializes the Employee object created in the
SerializeDemo program.
Ex:
import java.io.*;
public class DeserializeDemo {
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
Output:
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101
Example 2
Serialization
In this example, we are going to serialize the object of Student class. The writeObject()
method of ObjectOutputStream class provides the functionality to serialize the object. We
are saving the state of the object in the file named f.txt.
Ex:
import java.io.*;
class Persist{
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Deserialization
Ex:
import java.io.*;
class Depersist{
public static void main(String args[]){
try{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
211 ravi