Serialization and deserialization of Hashtable.
- By Huw Evans
- September 12, 2000
JAVA PRIMERUsing Java Object Serialization: A Few Pitfalls
Huw Evans
Listing 3. Serialization and deserialization of Hashtable.
import java.io.*;
import java.util.Hashtable;
public class Test
{
public static Object deserialize()
{
ObjectInputStream in = null;
FileInputStream in_file = null;
Object o = null;
try {
in_file = new FileInputStream("store");
in = new ObjectInputStream(in_file);
o = in.readObject();
in.close();
} catch(java.io.IOException ioe) {
ioe.printStackTrace();
System.exit(3);
}
return o;
}
public static void serialize(Object root)
{
ObjectOutputStream out = null;
FileOutputStream out_file = null;
try {
out_file = new FileOutputStream("store");
out = new ObjectOutputStream(out_file);
out.writeObject(root);
out.close();
} catch(java.io.IOException ioe) {
ioe.printStackTrace();
System.exit(1);
} catch(java.lang.ClassNotFoundException cnfe) {
cnfe.printStackTrace();
System.exit(2);
}
}
public static void main(String argv[])
{
Hashtable table = new Hashtable();
Key k = new Key();
Value v = new Value();
table.put(k, v);
System.out.println("Value: " + table.get(k));
System.out.println("Writing table: " + table);
serialize(table);
Hashtable new_table = (Hashtable) deserialize();
System.out.println("Reading table: " + new_table);
System.out.println("Value: " + new_table.get(k));
}
}