How do I serialize a hashtable?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Thursday, June 14, 2001 12:36 PM

I have a method for serializing a hashtable. _cache is the hashtable, and _cachefile is the name of the file to serialize to (both are global variables in a servlet class). Here is my method: ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(_cachefile)); os.writeObject(_cache); os.close(); Am I missing something? When I call this method, my hashtable is serializing, but none of the data is saved. Every single key and value in the hashtable is a String (which is serializable), but when I go to load the object, the hashtable I load is empty! Thanks for the help, ~Matt    More>>

I have a method for serializing a hashtable. _cache is the hashtable, and _cachefile is the name of the file to serialize to (both are global variables in a servlet class).



Here is my method:



			
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(_cachefile));

os.writeObject(_cache);

os.close();



Am I missing something? When I call this method, my hashtable is serializing, but none of the data is saved. Every single key and value in the hashtable is a String (which is serializable), but when I go to load the object, the hashtable I load is empty!




Thanks for the help,

~Matt    <<Less

Re: How do I serialize a hashtable?

Posted By:   Tim_Rohaly  
Posted On:   Thursday, June 14, 2001 01:27 PM

Works for me - I don't know what you're doing wrong,
but it is your code which is bad.
Here is my test code:

import java.io.*;
import java.util.*;

public class hash {

public static void main(String[] args) throws Exception {
// create hashtable
Hashtable numbers = new Hashtable();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));

// write out hashtable
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("hash.ser"));
out.writeObject(numbers);
out.flush();
out.close();

// read in hashtable
ObjectInputStream in = new ObjectInputStream(new FileInputStream("hash.ser"));
Hashtable table = (Hashtable) in.readObject();
in.close();

Enumeration keys = table.keys();
System.out.println("Deserialized Hashtable contains:");
while (keys.hasMoreElements()) {
String s = (String) keys.nextElement();
System.out.println(" key=" + s +
" value=" + (Integer) table.get(s));
}
}
}
About | Sitemap | Contact