1

I use a HashMap in order to store some keys and it's values like the following.

Map<String, String> map = new HashMap<String, String>();
map.put(key, value);

How can it be possible to store the data from HashMap before closing my app and retrieve them when I open the application next time in order to be able to add a new entry to the already entries. Can somebody help me?

4

1 回答 1

2

您可以使用序列化。它将您的数据写入硬盘驱动器上的文件中,您将能够在重新启动应用程序时加载它们。

由于您使用 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();
于 2013-09-22T17:18:15.360 回答