简体   繁体   English

将 Hashmap 写入文件

[英]Writing Hashmap to a file

I have an issue in writing a Hashmap to a file.我在将 Hashmap 写入文件时遇到问题。

Here is the code这是代码

    public HashMap<String, String> itemMap;

    public void SaveMapItem()
    {
        this.itemMap = new HashMap<String,String>();
        for (Item item:itemList)
        {
            itemMap.put(item.Name,item.Selected);
            Log.d(TAG,item.Name +" "+ item.Selected);
        }


        File file = new File(getDir("item", MODE_PRIVATE), "itemMap");
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
            outputStream.writeObject(itemMap);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public class Item
    {
    String Name;
    String Nickname;
    String Selected;

    public Item()
    {
        Name = "default";
        Nickname = "default";
        Selected = "false";
    }

    }

And here is the output (itemMap):这是 output (itemMap):

    �� sr java.util.HashMap���`� F 
    loadFactorI     thresholdxp?@     w      t 
    ITEM-00015t falset 
    ITEM-00019q ~ t 
    ITEM-00018q ~ t 
    ITEM-00002q ~ x

In this example, all the items should be false.在这个例子中,所有的项目都应该是假的。 I even tried using boolean as the value of the hashmap ( HashMap<String, String> ) but they suggested I use String.我什至尝试使用 boolean 作为 hashmap ( HashMap<String, String> ) 的值,但他们建议我使用 String。 Is it correct?这是对的吗?

I found the issue.我发现了这个问题。 There is no issue.没有问题。 The values are all the same and the system uses the value ~ for all the same entry.这些值都是相同的,系统对所有相同的条目使用值 ~。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM