我使用HashMap来存储一些键,它的值如下所示。
Map<String, String> map = new HashMap<String, String>();
map.put(key, value);在关闭我的应用程序之前,如何能够在下一次打开应用程序时从HashMap存储数据并检索它们,以便能够向已经存在的条目添加一个新条目。有人能帮我吗?
发布于 2013-09-22 17:18:15
您可以使用序列化。它会将你的数据写在硬盘上的一个文件中,当你重新启动应用程序时,你就可以加载它们了。
由于您使用字符串作为键和值,并且String实现了可序列化,所以应该很容易。
以下是如何编写:
File file = new File("nameOfYourFile");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(yourHashMap);
s.close();并改为:
File file = new File("temp");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject();
s.close();https://stackoverflow.com/questions/18946537
复制相似问题