Monday 14 November 2016

Example of Serialization, ObjectInputStream, ObjectInputStream:



import java.io.*;
classMyclass implements Serializable
{
 String name;int roll;
double marks;
publicMyclass(String n,intr,double m)
 {
name=n;
roll=r;
marks=m;
 }
public String toString()
 {
return "\nName : "+name+"\nRoll : "+roll+"\nMarks : "+marks;
 }
}
class Serial
{
public static void main(String args[])
 {
try {
Myclass m1=new Myclass("Santosh",1,750);
System.out.println("Object for Writting: "+m1);
FileOutputStream f1=new FileOutputStream("Myserial.txt");
ObjectOutputStream o1=new ObjectOutputStream(f1);
o1.writeObject(m1);
o1.flush();
o1.close();
  }
catch(IOException e)
  {
System.out.println("\nException in serialization");
  }
try {
Myclass m2;
FileInputStream f2=new FileInputStream("Myserial.txt");
ObjectInputStream o2=new ObjectInputStream(f2);
   m2=(Myclass) o2.readObject();
o2.close();
System.out.println("\nObject after Reading : "+m2);
  }
catch(Exception e)
  {
System.out.println("\nException in deserialization");
  }
 }
}
Output:
Object for writing:
Name: Santosh
Roll: 1
Marks: 750.0
Object after reading:
Name: Santosh
Roll: 1
Marks: 750.0


No comments:
Write comments