Java:如何将HashMap >>写入文件?

所以我能够写:

HashMap<String, ArrayList<Integer>> ...

但是当涉及到像

HashMap<String, HashMap<Integer, ArrayList<Integer>>> ...

我失败了…

Set<String> keys = outer.keySet();
List<String> list = sortList(keys);
Iterator<String> it = list.iterator();
HashMap<Integer,ArrayList<Integer>> inner=new HashMap<Integer,ArrayList<Integer>>();
                while (it.hasNext()) {
                    String key = it.next();
                    Set<Integer> ids= inner.keySet();
                    List<Integer> positions=sortList(ids);
                    Iterator<Integer> itIn=positions.iterator();
                    while(itIn.hasNext()){
                        String id= it.next();
                        output.write(key + "\t" + outer.get(key) + " " +inner.get(id) +"\n");
                    }
                }

我的代码可以编写外部has的所有键以及Integer1的第一个元素,但看不到列表等.
如何与内部哈希图和外部哈希图建立连接?

解决方法:

如何通过ObjectOutputStream将整个对象存储为文件?就像是:

public static void saveObject(HashMap<String, HashMap<Integer, ArrayList<Integer>>> obj, String filePath)
{
    OutputStream os = null;
    try
    {
        os = new ObjectOutputStream(new FileOutputStream(filePath));
        os.writeObject(obj);
    }
    catch(Exception ex){}
    finally
    {
        os.close();
    }
}

然后您可以像这样加载它:

public static HashMap<String, HashMap<Integer, ArrayList<Integer>>> loadObject(String filePath)
{
    HashMap<String, HashMap<Integer, ArrayList<Integer>>> obj = null;
    InputStream is = null;
    try
    {
        is = new ObjectInputStream(new FileInputStream(filePath));
        obj = (HashMap<String, HashMap<Integer, ArrayList<Integer>>>) is.readObject();
    }
    catch(Exception ex){}
    finally
    {
        is.close();
    }
    return obj;
}

请注意,您需要实现Serializable接口才能使用此对象序列化.

上一篇:php-如何在Magento中获得属性选项的位置?


下一篇:[CF1498D]Bananas in a Microwave