Object Serialization and DeSerialization
This class writes an int primitive data type, a String and a Date Object which are predefined java class files that implements serializable interface into persistance storage.
import java.io.*;
import java.util.*;
class ObjectSeril {
public static void main(String[] args) {
int t =50000;
try {
FileOutputStream out = new FileOutputStream("theTime.tmp");
ObjectOutputStream s = new ObjectOutputStream(out);
s.writeObject("Today");
// s.writeObject(t); Only Objects
s.writeObject(new Date());
s.flush();
} catch(IOException e) {
System.out.println(e);
}
FileInputStream out = new FileInputStream("theTime.tmp");
ObjectInputStream s = new ObjectInputStream(out);
String str = (String) s.readObject();
System.out.println(str);
int in = s.readInt();
System.out.println(in);
System.out.println(d);
s.close();
} catch(IOException e1) {
System.out.println(e1);
}catch(ClassNotFoundException e2) {
System.out.println(e2);
}
}
}
Thus, the writeObject method serializes the specified object, traverses its references to other objects recursively, and writes them all. In this way, relationships between objects are maintained.
How to Read from an ObjectInputStream
import java.util.*;
public static void main(String[] args) {
int t =50000;
try {
MyClass mclass = new MyClass(10, 20.5, "vishnu");
System.out.println("MyClass Object:");
System.out.println("~~~~~~~~~~~~~");
System.out.println("Before Serialization:");
System.out.println(mclass + "\n");
FileOutputStream out = new FileOutputStream("theTime");
ObjectOutputStream s = new ObjectOutputStream(out);
s.writeObject(mclass);
s.flush();
} catch(IOException e) {
System.out.println(e);
}
MyClass myclass;
FileInputStream in = new FileInputStream("theTime");
ObjectInputStream s = new ObjectInputStream(in);
myclass = (MyClass) s.readObject();
System.out.println("After Serialization:");
System.out.println(myclass);
s.close();
} catch(IOException e1) {
System.out.println(e1);
}catch(ClassNotFoundException e2) {
System.out.println(e2);
}
}
}
transient double d;
String str;
this.in = in;
this.d = d;
this.str = str;
}
return "int value: " + in + " double value: " + d + " string value: " + str;
}
}
Output
MyClass Object:
~~~~~~~~~~~~~
Before Serialization:
int value: 10 double value: 20.5 string value: vishnu
After Serialization:
int value: 10 double value: 0.0 string value: vishnu


