我使用 HashMap 来存储一些键及其值,如下所示。
Map<String, String> map = new HashMap<String, String>();
map.put(key, value);
如何才能在关闭我的应用程序之前存储来自 HashMap 的数据,并在我下次打开应用程序时检索它们,以便能够向已有条目添加新条目。有人可以帮助我吗?
最佳答案
您可以使用序列化。它会将您的数据写入硬盘驱动器上的文件中,您将能够在重新启动应用程序时加载它们。
由于您将 String 用作键和值,并且 String 实现了 Serializable,所以应该很容易。
写法如下:
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();
关于java - 关闭 Android 应用程序后 HashMap 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18946537/