De-serialization is a process of reducing the data from the file in the form of object.
Steps for developing deserialization process:
1. Create an object of that class which was serialized.
For example:
Student so=new Student ();
2. Choose the file name and open it into read mode with the help of FileInputStream class.
For example:
FileInputStream fis=new FileInputStream ("Student");
3. Create an object of ObjectInputStream class. The Constructor of ObjectInputStream class is taking an object of FileInputStream class.
For example:
ObjectInputStream ois=new ObjectInputStream (fis);
4. ObjectInputStream class contains the following method which will read the entire object or record.
public Object readObject ();
For example:
Object obj=ois.readObject ();
5. Typecast an object of java.lang.Object class into appropriate Serializable sub-class object for calling get methods which are specially defined in Serializable sub-class.
For example:
So= (Student) obj;
6. Apply set of get methods for printing the data of Serializable sub-class object.
For example:
int stno=so.getStno (); String sname=so.getSname (); flaot marks=so.getMarks ();
7. Close the chained stream.
For example:
fis.close (); ois.close ();
Write a JAVA program to retrieve or de-serialize student data?
Answer:
import java.io.*; import sp.Student; class DeSerial { public static void main (String [] args) { try { Student so=new Student (); DataInputStream dis=new DataInputStream (System.in); System.out.println ("ENTER FILE NAME TO READ"); String fname=dis.readLine (); FileInputStream fis=new FileInputStream (fname); ObjectInputStream ois=new ObjectInputStream (fis); Object obj=dis.readObject (); so=(Object) obj; System.out.println ("STUDENT NUMBER "+so.getStno ()); System.out.println ("STUDENT NAME "+so.getSname ()); System.out.println ("STUDENT MARKS "+so.getMarks ()); fis.close (); ois.close (); } catch (FileNotFoundException fnfe) { System.out.println ("FILE DOES NOT EXISTS"); } catch (Exception e) { System.out.println (e); } } };
Types of serialization:
In java we have four types of serialization; they are complete serialization, selective serialization, manual serialization and automatic serialization.
In order to avoid the variable from the serialization process, make that variable declaration as transient i.e., transient variables never participate in serialization process.
class RegStudent extends Student { ............. ............. };