Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we write a Hashtable to a file?

Tags:

java

hashtable

I have a Hashtable<string,string>, in my program I want to record the values of the Hashtable to process later.

My question is: can we write object Hastable to a file? If so, how can we later load that file?

like image 240
tiendv Avatar asked May 11 '10 05:05

tiendv


People also ask

How do you store hash tables?

In separate chaining, each element of the hash table is a linked list. To store an element in the hash table you must insert it into a specific linked list. If there is any collision (i.e. two different elements have same hash value) then store both the elements in the same linked list.

Should I use Hashtable or HashMap?

Hashmap vs Hashtable It is thread-safe and can be shared with many threads. HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value. HashMap is generally preferred over HashTable if thread synchronization is not needed.

Is Hashtable immutable?

A hash table is also either mutable or immutable; immutable tables support constant-time functional update. A hash table can be used as a two-valued sequence (see Sequences). The keys and values of the hash table serve as elements of the sequence (i.e., each element is a key and its associated value).

Is a Hashtable an array?

A hashtable is a data structure, much like an array, except you store each value (object) using a key.


1 Answers

Yes, using binary serialization (ObjectOutputStream):

FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(yourHashTable);
oos.close();

Then you can read it using ObjectInputStream

The objects that you put inside the Hashtable (or better - HashMap) have to implement Serializable


If you want to store the Hashtable in a human-readable format, you can use java.beans.XMLEncoder:

FileOutputStream fos = new FileOutputStream("tmp.xml");
XMLEncoder e = new XMLEncoder(fos);
e.writeObject(yourHashTable);
e.close();
like image 65
Bozho Avatar answered Oct 02 '22 20:10

Bozho