我们可以将哈希表写入文件吗?

2022-09-04 02:18:21

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

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


答案 1

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

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

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

然后你可以阅读它使用ObjectInputStream

您放在(或更好的 - )中的对象必须实现HashtableHashMapSerializable


如果要以人类可读的格式存储 ,可以使用:Hashtablejava.beans.XMLEncoder

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

答案 2

不知道您的特定应用程序,但您可能希望查看 Properties 类。(它扩展了哈希映射。

本课程为您提供

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.

本教程也非常有教育意义。