【问题标题】:adding hashmap object to internal memory every time每次都将 hashmap 对象添加到内存中
【发布时间】:2013-02-07 14:55:21
【问题描述】:

我有一个 hashmap 对象,我保存在内部存储器中,但每次它替换 hashmap 对象而不是添加,每次调用此方法时如何添加 hasmap 对象:

这是我的代码:

public void saveDataInInternalStorage(Context context, HashMap<String, HashMap<String, String>> hashMapObject,
        String fileName) {
    try {
        File file = new File(context.getDir("data", MODE_PRIVATE), fileName);
        // if (file.exists()) {
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream outputStream = new ObjectOutputStream(fos);
        outputStream.writeObject(hashMapObject);
        outputStream.flush();
        outputStream.close();
        // }
    } catch (FileNotFoundException e) {
        // e.printStackTrace();
    } catch (IOException e) {
        // e.printStackTrace();
    }
    }

【问题讨论】:

    标签: android storage internal


    【解决方案1】:

    只需更改此行:

     FileOutputStream fos = new FileOutputStream(file, true);
    

    true告诉 FOS 将内容附加到文件中,而不是覆盖 ist。

    【讨论】:

    • 好的,最初我的 hasmap 将收到 ("a",1) ("b",2) 现在下次我发送 ("c",1) ("d",2)...所以当我迭代它时,我会用你的代码获得所有这些值吗?
    • 您没有发布任何迭代代码。也许您只是从文件中读取了第一行或其他内容。
    • 这是我的代码:Iterator itr = testStats.entrySet().iterator(); while (itr.hasNext()) { Map.Entry 对 = (Map.Entry)itr.next(); System.out.println("KEY "+pairs.getKey() + " VALUE = " + pairs.getValue()); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2013-05-17
    • 2017-02-16
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多