Saturday, February 25, 2012

SerializationDemo

import java.io.*;
public class SerilizationExm {

public static void main(String args[])
{
int i=10;
int j=0;
long start = System.currentTimeMillis ();
//Serializing object

MyClass2 a= new MyClass2();
try {
MyClass1 object1=new MyClass1("Anand",27,1984,a);
System.out.println("Object1:     "+object1);
FileOutputStream fos=new FileOutputStream("Stream");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(object1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
MyClass1 object2;
//System.exit (0);
//Runtime.getRuntime().exit(0);
FileInputStream fis=new FileInputStream("Stream1");
ObjectInputStream ois=new ObjectInputStream(fis);
object2=(MyClass1)ois.readObject();
System.out.println("Object2:     "+object2);
//System.exit (0);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("File name mentioned does not exists");
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
System.out.println("This is finally Method"+i/j);
}
catch(ArithmeticException e)
{
System.out.println("Exception in finally");
//e.printStackTrace();
}
}
long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start)+"  In milli seconds");
}
}

 class MyClass1 implements Serializable
 {
String s;
static  int c=2;
String d;
int a;
long b;
public MyClass1(String ab,int bc,long ac,MyClass2 abc )
{
s=ab;
a=bc;
b=ac;
d=abc.aMethod();
}

public String toString()
{
//d=(new MyClass2()).aMethod();
return "s="+s+";a="+a+";b="+b+";c="+c+";d="+d;
}


 }

 class MyClass2
 {
public String aMethod()
{
return "Prakash";
}
 }

No comments:

Post a Comment