我有一个Hashtable<string,string>,在我的程序中,我想记录Hashtable的值,以便稍后处理.
我的问题是:我们可以将对象Hastable写入文件吗?如果是这样,我们以后如何加载该文件?
是的,使用二进制序列化(ObjectOutputStream):
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(yourHashTable);
oos.close();
Run Code Online (Sandbox Code Playgroud)
然后你可以用它来阅读它 ObjectInputStream
您放入Hashtable(或更好 - HashMap)的对象必须实现Serializable
如果要以Hashtable人类可读的格式存储,可以使用java.beans.XMLEncoder:
FileOutputStream fos = new FileOutputStream("tmp.xml");
XMLEncoder e = new XMLEncoder(fos);
e.writeObject(yourHashTable);
e.close();
Run Code Online (Sandbox Code Playgroud)
不了解您的特定应用程序,但您可能希望查看Properties类.(它扩展了hashmap.)
本课程为您提供
Run Code Online (Sandbox Code Playgroud)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.
该教程也很有教育意义.
| 归档时间: |
|
| 查看次数: |
10575 次 |
| 最近记录: |