我们可以将Hashtable写入文件吗?

时间:2010-05-11 05:25:55

标签: java hashtable

我有一个Hashtable<string,string>,在我的程序中,我想记录Hashtable的值,以便稍后处理。

我的问题是:我们可以将对象Hastable写入文件吗?如果是这样,我们以后如何加载该文件?

4 个答案:

答案 0 :(得分:9)

是的,使用二进制序列化(ObjectOutputStream):

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

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

然后您可以使用ObjectInputStream

阅读它

您放在Hashtable(或更好 - HashMap)内的对象必须实施Serializable


如果您想以人类可读的格式存储Hashtable,可以使用java.beans.XMLEncoder

FileOutputStream fos = new FileOutputStream("tmp.xml");
XMLEncoder e = new XMLEncoder(fos);
e.writeObject(yourHashTable);
e.close();

答案 1 :(得分:5)

不了解您的具体应用,但您可能需要查看Properties class。 (它扩展了hashmap。)

本课程为您提供

void  load(InputStream inStream)
     Reads a property list (key and element pairs) from the input byte stream.
void  load(Reader reader)
     Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format.
void  loadFromXML(InputStream in)
     Loads all of the properties represented by the XML document on the specified input stream into this properties table.
void  store(Writer writer, String comments)
      Writes this property list (key and element pairs) in this Properties table to the output character stream in a format suitable for using the load(Reader) method.
void  storeToXML(OutputStream os, String comment)
      Emits an XML document representing all of the properties contained in this table.

The tutorial也非常有教育意义。

答案 2 :(得分:1)

如果您希望能够在写完地图后轻松编辑地图,您可能需要查看jYaml。它允许您轻松地将地图写入Yaml格式的文件,这意味着它易于阅读和编辑。

答案 3 :(得分:0)

您还可以使用 MapDB ,它会在您执行putcommit后为您保存HashMap。 这样,如果程序崩溃,那么值仍将保持不变。