//Note: First Execute Demo1 for writing objects and then Demo2 for reading objects
//[1]
//Object Serialization in Java: Writing objects in to a file
import java.io.*;
class A implements Serializable{
int i=75;
}
class Demo1{//writing through byte stream Object Serialization in java
public static void main(String arg[]) throws IOException{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("one.txt"));
A a=new A();
oos.writeObject(a);
oos.writeObject(new String("sun"));
oos.writeObject(new StringBuffer("micro"));
oos.writeObject(new StringBuilder("system"));
oos.close();
}
}
//[2]
//Object Serialization in Java: Reading objects from the file
import java.io.*;
class A implements Serializable{
int i=75;
}
class Demo2{//reading from byte stream Object Serialization in java
public static void main(String arg[]) throws Exception{
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("one.txt"));
A a=(A)ois.readObject();
String s=(String)ois.readObject();
StringBuffer s1=(StringBuffer)ois.readObject();
StringBuilder s2=(StringBuilder)ois.readObject();
ois.close();
System.out.println(a.i);
System.out.println(s);
System.out.println(s1);
System.out.println(s2);
}
}
No comments:
Post a Comment