Thursday, May 30, 2013

Serialization and De-Serialization In Java



SERIALIZATION:
·         When we use the normal streams to read and write the data to and from the file, there is a possibility for performing unnecessary read and write operations because of this there is a possibility of loosing the performance of java program.
·         In order to improve the performance of java program by perform single read and write operation irrespective number of fields we must use the concept of Serialization.
·         DEFINITION: Serialization is a mechanism of saving the state of the entire object at a time on to a file.
·         Steps for developing serializable subclass:
o   Choose the appropriate package name.
o   Choose the appropriate user defined serializable sub class name.
o   Whichever class we have chosen in previous step must be implementing a predefined interface call java.io.Serializable. Serializable interface does not contain any abstract method i.e. Marker/Marked/Tagged interface.
o   Choose the set of data members in serializable sub class.
o   Choose the set of setR() methods for each and every data member of the serializable sub class. The set of setR() methods are also known as mutators or modifiers whose general form is as follows:
public void setXXX (data-type variable)
{
}
Where XXX represents the data member of serializable sub class
o   Choose the set of getR() methods for each and every data member of the serializable sub class. The set of getR() methods are also known as inspectors whose general form is as follows:
public data-type getXXX()
{
}
Where XXX represents the data member of the serializable sub class
Note: If any class is containing set of getR() and setR() methods then that class is known as javaBean or POJO(Plain Old Java Object) class and such type of programming is known as Component Based Style Programming.
o   Develop a serializable sub class for Student.
package p;

Import java.io.*;

public class Student implements Serializable

{

private int stNo;

                private String stName;

                private float stMarks;

                                               

public void setStNo(int stNo)

                {

                                this.stNo=StNo;

}

                public void setStName(int stName)

                {

                                this.stName=StName;

}

                public void setMarks(int marks)

                {

                                this.marks=Marks;

}

public int getStNo()

{

                return(stNo);

}

public String getStName()

{

                return(stName);

}

public float getStMarks()

{

                return(marks);

}

}

o   Develop a Serialization process program:
import java.io.*;

class SerializationProcessDemo

{

public static void main(String args[]) throws Exception

                {

                                DataInputStream dis=new DataInputStream(System.in);

                                p.Student s=new p.Student();

                                System.out.println(“Enter Student # : ”);

                                int rollnum=Interger.parseInt(dis.readLine());

                                System.out.println(“Enter Student Name : ”);

                                String sName=dis.readLine();

                                System.out.println(“Enter Student Marks:”);

                                float marks=Float.parseFloat(dis.readLine());



                                s.setStNo(rollNumber);

                                s.setStName(sName);

                                s.setMarks(marks);



                                System.out.println(“Enter the filename where you want to write the object: ”);

                                String fName=dis.readLine();



                                FileOutputStream fos=new FileOutputStream(fName);

                                ObjectOutputStream oos=new ObjectOutputStream(fos);

                                oos.writeObject(s);

               

                                dis.close();

                                fos.close();

                                oos.close();

}

}





DESERIALIZATION:
·         It is a mechanism of retrieving the records from the file into the main memory of the computer or it is the ability of retrieving one stream object into the main memory of the computer is known as Deserialization.
·         STEPS FOR DESERIALIZATION PROCESS:
(1)    Create an object of serializable subclass.
(2)    Choose the file name and open it into read mode with the help of FileInputStream class.
(3)    An object of FileInputStream class will not read the entire record at once hence it is recommended to create an object of ObjectInputStream class. ObjectInputStream class contains the following constructor which takes an object of FileInputstream class as a parameter.
ObjectInputStream (FileInputStream)

(4)    ObjectInputStream class contains the following method which will read the entire object at a time from the file and it returns an object of Object class.
public Object readObject();
(5)    Type cast the object of Object class into corresponding serializable subclass object for calling specific methods of serializable subclass.
(6)    Call set of getR() to get the data from serializable subclass object.
(7)    Close the file which is opened in read mode and close all stream.

Sample Program:


import java.io.*;

class DeserializationDemo

{

        public static void main(String aa[])

        {

                        try

{

                p.Student s =new p.Student();

                DataInputStream dis=DataInputStream (System.in);

                System.out.println(“Enter the filename you want to read from : ”);

                String fName=dis.readLine();

                FileInputStream fis=new FileInputStream(fName);

                ObjectInputStream ois=new ObjectInputStream(fis);

                Object obj = ois.readObject();

                s  = (Student)obj;                                             //type casting

                System.out.println(“Student # : ”+s.getStNo());

                System.out.println(“Student Name : ”+s.getStName());

                System.out.println(“Student Marks : ”+s.getStMarks());

}

catch(FileNotFoundException fe)

{

                e.printStackTrace();

}

}

}



NOTE: In order to develop a complete Serializable application, we must develop 3 programs-

(1)    Serializable subclass program [Student.java]
(2)    Serialization process program [SerializationProcess.java]
(3)    Deserialization process program [DeserializationDemo.java]


 ===================================================

Input/Output (i/o) and File Handling



IO STREAMS / FILE HANDLING


·         In java, we can develop two types of applications. They are:
o   Non-persistent or Volatile Program.
o   Persistent or Non-Volatile Program.
A non persistent program is one whose result is stored temporary of the Main Memory of the computer.
A persistent program is one in which the result of the program is stored permanently in secondary storage devices such as hard disk drive, floppy disk drive etc.
·         To store the data permanently we have two approaches, they are
(a)    Using files
(b)   Using database

·         We can store the data permanently in the form of a file, but files do not provide any security to prevent from unauthorized modifications. Hence the real world applications are not storing the data in the form of files.
Therefore, all the real world transactions and there results are recommended to store in the form of database. Since most of the database products are providing security features to prevent from unauthorized modification.

NOTE:
FILE DEFINITION:              Collection of records is known as File.
RECORD DEFINITION:     Collection of field values is known as Record.

·         In order to deal with file handling we must import a package called java.io.* package. This package contains collection of classes and Interfaces to perform operation on to the file.
·         As a part of file handling we are getting two types of Exceptions. They are:
(a)    java.io.FileNotFoundException.
(b)   java.io.IOException.
·         FileNotFoundException takes place when the required file is not found in the hard disk.
·         IOException takes place in java program in two circumtances:
(a)    When we try to write the data on to the read-Only file.
(b)   When we try to create a file and the hard disk is full.
·         java.io.IOException is the super class for java.io.FileNotFoundException.
Types of operations on to the file:
(a)    Read operation
(b)   Write operation







Streams:
·         Flow of data from primary memory to secondary memory and vice-versa is known as Stream.
·         Based on amount of data being transferred between primary memory and secondary memory, in java we have two types of Streams. They are:
(i)                  Byte Stream – 1 byte of data will be transmitted at a time (Low level Application)
(ii)                Character Stream – 2 bytes of data will be transmitted at a time (Higher Level application Internet Programming)

·         Byte Stream: Byte Streams are those in which 1 byte of data will be transferred at a time between main memory and secondary memory and vice versa.
·         Hierarchy chart of Byte Stream:


(1)    java.io.InputStream Class:
·         InputStream class is an abstract class.
·         This class is basically used to open the file in read mode.
·         Opening the file in the read mode is nothing but creating an object of InputStream class indirectly whose object allows us to read only 1 byte at a time.

Methods in InputStream class:
a.    public int available():
This method is used for determining the size of the file. If the specified file is not available in HDD then we get FileNotFoundException.

b.      public int read();
It is used for reading the data from the file until the end of the file is not taking place. In java end of the file is indicated by “-1” (it is placed by JVM and its Unicode char is ÿ).

c.       public void close();
This method is used for closing the file if the file is opened in read mode.

(2)    java.io.OutputStream Class:
·         OutputStream class is an abstract class.
·         OutputStream class is used for opening a file in write mode but the disk space must be there otherwise it will throw an IOException.
·         Opening a file in write mode is nothing but creating an object of OutputStream class indirectly.
Methods in InputStream class:
a.    public int available():
This method is used for determining the size of the file. If the specified file is not available in HDD then we get FileNotFoundException.

d.      public void write(int);
It is used for writing the data to the file. After opening a file in write mode, we can write our own data and at the end of the file -1 will be appended by the JVM to indicate the end of the file.

e.      public void close();
This method is used for closing the file if the file is opened in write mode.

(3)    Java.io.DataInputStream class:
·         DataInputStream class is a concrete subclass of all input stream classes.
·         DataInputStream class is used for 2 purposes. They are:
o   Reading the data from input device called keyboard.
o   It is also used for reading the data from other machine which is located in other network.
·         Reading the data either locally or globally is nothing but creating an object of DataInputStream class.
·         DataInputStream class API:
o   Constructor: DataInputStream (InputStream)
o   InputStream is an abstract class whose object cannot be created directly but it can be created indirectly.
o   An object of InputStream class called “in” which is created as a static data member in System class, Hence an object of InputStream class is “System.in”.
o   For example: DataInputStream dis = new DataInputStream (System.in);
·         Instance Methods:
o   public byte readByte();
o   public short readShort();
o   public int readInt();
o   public long readLong();
o   public float readFloat();
o   public double readDouble();
o   public char readChar();
o   public boolean readBoolean();
o   public String readLine(); 



Note: public void readLine() method is used for reading any kind of data and it is available in the form of String object.
·         Sample Program:
import java.io.*;
class DataInputStreamDemo
{
                                public Static void main(String args[]) throws Exception
{
DataInputStream dis = new DataInputStream (System.in);

System.out.println(“Enter first value : ”);
int n1= Integer.parseInt(dis.readLine());

System.out.println(“Enter second value : ”);
int n2=  Integer.parseInt(dis.readLine());

int n =n1+n2;
System.out.println(“Sum of”+n1+”and ”+n2+”:”+n3);
}
}

(4)    java.io.DataOutputStream class:
·         DataOutputStream class is a concrete subclass of all output stream classes.
·         DataOutputStream is used 2 purposes. They are:
                                                               i.      To display the data onto the console.
                                                             ii.      Writing the data on some other machine which is located on some other network.
·         To achieve the above purpose, we need to create an object of DataOutputStream class.
·         DataOutputStream class API:
o   Constructor: DataOutputStream (OutputStream)
o   OutputStream is an abstract class whose object cannot be created directly but it can be created indirectly.
o   An object of OutputStream class called “out” which is created as a static data member in System class, Hence an object of InputStream class is “System.out”.
o   For example: DataOutputStream dos = new DataOutputStream (System.out);
·         Instance Methods:
o   public void write(byte);
o   public void write(short);
o   public void write(int);
o   public void write(long);
o   public void write(float);
o   public void write(double);
o   public void write(char);
o   public void write(boolean);

o   public void writeByte(byte);
o   public void writeShort(short);
o   public void writeInt(int);
o   public void writeLong(long);
o   public void writeFloat(float);
o   public void writeDouble(double);
o   public void writeChar(char);
o   public void writeBoolean(boolean);

(5)    java.io.FileInputStream Class:
·         It is a concrete subclass of all Inputstream classes.
·         When we want to open a file in read mode, we must create an object of FileInputStream class by using its constructor.
·         Constructor: FileInputStream (String ilename) throws FileNotFoundException
Here String ilename represents the name of the file to be opened in read mode.

·         Opening a file in read mode:
FileInputStream fis= new FileInputStream (“abc.txt”);
·         When, we are opening a file, there can be 2 cases:
o   The file may exist in the hard disk.
If “abc.txt” exists in the hard disk then it will be opened successfully in read mode and whose address is available or stored in “fis” (Object of FileInputStream class) and “fis” is pointing to the first entry of the file “abc.txt”.



o   The file may not exist in the hard disk.
If “abc.txt” file does not exist in hard disk then object “fis” contains null and we get an Exception called FileNotFoundException.
(6)    java.io.FileOutPutStream class:
·         FileOutputStream class is a concrete subclass of all outputStream classes.
·         FileOutputStream class is used for opening a file in write mode.
·         Opening a file in write mode is nothing but creating an object of FileOutputStream class.
·         FileOutputStream class API:
Constructor:
·         FileOutputStream (String fileName)
·         FileOutputStream (String filename, boolean flag).

Example for first constructor:
FileOutPutStream fos = new FileOutPutStream (“abc.txt”);
·         When, we are opening a file, there can be 2 cases:
o   The file is existing in the hard disk and boolean value is false by default.
If “abc.txt” exists in the hard disk then it will be opened successfully in write mode and whose address is available or stored in “fos” (Object of FileOutputStream class) and “fos” is pointing to the first entry of the file “abc.txt”.  When we perform write operation on to the file, the existing data will be replaced with new data.

o   The file is not existing in the hard disk and boolean if false by default.
If “abc.txt” file does not exist in hard disk then the file will be created first if and only if there are sufficient disk space, otherwise it will throw IOException. After creation of the file, it will be opened successfully in write mode and “fos” contains the address of the file and points to the first entry of the file.


Example for second constructor:
FileOutPutStream fos = new FileOutPutStream (“abc.txt”, true/false);
·         When, we are opening a file, there can be 3 cases:
o   The file is existing in the hard disk and boolean value is true.

If “abc.txt” exists in the hard disk then it will be opened successfully in write mode and whose address is available or stored in “fos” (Object of FileOutputStream class) and “fos” is pointing to the next to the end of the file “abc.txt”.  When we perform write operation on to the file, the existing data will remain same and new data will be appended next to the existing data.


o   The file is existing in the hard disk and boolean value is false.

If “abc.txt” exists in the hard disk then it will be opened successfully in write mode and whose address is available or stored in “fos” (Object of FileOutputStream class) and “fos” is pointing to the first entry of the file “abc.txt”.  When we perform write operation on to the file, the existing data will be replaced with new data.

o   The file not existing in the hard disk and boolean value is true/false.

If “abc.txt” does not exist in the hard disk then it will be created first and then will be opned successfully in write mode and whose address is available or stored in “fos” (Object of FileOutputStream class) and “fos” is pointing to the first entry of the file “abc.txt”.  When we perform write operation on to the file, data will be written simply as it does not have data i.e. newly created file.                                                                    

Sample Program:
Write a Java program to perform the following:
(1)    Create a file and write integer from -10 to 10.
(2)    Read integer from a file which is created at the previous step, by opening it into read mode.
Program to write the data in to a file:
import java.io.*;
Class FileOutputStreamDemo
{
                        public static void main(String arg[])
                        {
                                        DataInputStream dis =  new DataInputStream(System.in);
                                        System.out.println(“Enter the file name to be opened in write mode : ”);
                                        String fileName = dis.readLine();
                                        FileOutputStream fos= new FileOutputStream (fileName);
                                        for (int i=-10; i<=10; i++)
                                        {
                                                        fos.write(i);
}
fos.close();
dis.close();
}
}
                                Program to read the data from a file:
import java.io.*;
Class FileInputStreamDemo
{
                        public static void main(String arg[])
                        {
                                        DataInputStream dis =  new DataInputStream(System.in);
                                        System.out.println(“Enter the file name to be opened in read mode : ”);
                                        String fileName = dis.readLine();
                                        FileInputStream fis= new FileInputStream (fileName);
                                        int k=0;
                                        while(k!=-1)
                                        {
                                                        K=fis.read();
                                                        System.out.print(k);
}
fis.close();
dis.close();
}
}

================================================================