Can we write a Hashtable to a file?

假如想象 提交于 2019-12-30 02:08:09

问题


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?


回答1:


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();



回答2:


Don't know about your specific application, but you might want to have a look at the Properties class. (It extends hashmap.)

This class provides you with

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 is quite educational also.




回答3:


If you want to be able to easily edit the map once it's written out, you might want to take a look at jYaml. It allows you to easily write the map to a Yaml-formatted file, meaning it's easy to read and edit.




回答4:


You could also use MapDB and it will save the HashMap for you after you do a put and a commit. That way if the program crashes the values will still be persisted.



来源:https://stackoverflow.com/questions/2808277/can-we-write-a-hashtable-to-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!