Write LinkedHashMap to a text file?

This question already has an answer here:

  • How to efficiently iterate over each entry in a 'Map'? 38 answers
  • Iterate through a HashMap [duplicate] 7 answers

  • Because you're trying to write your entire Map to the file and not individual entries you could use writeObject() and readObject() like this:

    Map<String, String> m1 = new LinkedHashMap<String, String>(16, 0.75f, true);
    
    m1.put("John Smith", "555-555-5555");
    m1.put("Jane Smith", "444-444-4444");
    
    //Write to file
    FileOutputStream fout = new FileOutputStream("file.out");
    ObjectOutputStream oos = new ObjectOutputStream(fout);
    oos.writeObject(m1);
    
    //Read from file
    FileInputStream fin = new FileInputStream("file.out");
    ObjectInputStream ois = new ObjectInputStream(fin);
    Map<String, String> m2 = (LinkedHashMap<String, String>) ois.readObject();
    

    Hope this helps.

    链接地址: http://www.djcxy.com/p/17988.html

    上一篇: 从HashMap中删除条目

    下一篇: 将LinkedHashMap写入文本文件?