【问题标题】:How to write and read a file with a HashMap? [duplicate]如何使用 HashMap 读写文件? [复制]
【发布时间】:2012-09-26 17:02:12
【问题描述】:

我有一个HashMap 和两个字符串Map<String, String> ldapContent = new HashMap<String, String>

现在我想将Map 保存在一个外部文件中,以便以后使用Map 而无需再次初始化...

那么我必须如何保存Map 以便以后再次使用它?

【问题讨论】:

  • 你试过什么?可以手动使用Java序列化、XML、CSV、二进制数据...
  • 我只知道简单的文件阅读器。因此感谢序列化提示。我以前不知道...

标签: java file dictionary hashmap


【解决方案1】:

由于HashMap实现了Serializable接口,你可以简单地使用ObjectOutputStream类将整个Map写入文件,并使用ObjectInputStream类再次读取它

下面是解释ObjectOutStreamObjectInputStream用法的简单代码

import java.util.*;
import java.io.*;
public class A{

    HashMap<String,String> hm;
    public A() {
        hm=new HashMap<String,String>();

        hm.put("1","A");
        hm.put("2","B");
        hm.put("3","C");

        method1(hm);

    }

public void method1(HashMap<String,String> map) {
    //write to file : "fileone"
    try {
        File fileOne=new File("fileone");
        FileOutputStream fos=new FileOutputStream(fileOne);
        ObjectOutputStream oos=new ObjectOutputStream(fos);

        oos.writeObject(map);
        oos.flush();
        oos.close();
        fos.close();
    } catch(Exception e) {}

    //read from file 
    try {
        File toRead=new File("fileone");
        FileInputStream fis=new FileInputStream(toRead);
        ObjectInputStream ois=new ObjectInputStream(fis);

        HashMap<String,String> mapInFile=(HashMap<String,String>)ois.readObject();

        ois.close();
        fis.close();
        //print All data in MAP
        for(Map.Entry<String,String> m :mapInFile.entrySet()){
            System.out.println(m.getKey()+" : "+m.getValue());
        }
    } catch(Exception e) {}
  }

public static void main(String args[]) {
        new A();
}

}

或者如果你想将数据作为文本写入文件,你可以简单地遍历Map并逐行写入键和值,然后逐行再次读取并添加到HashMap

import java.util.*;
import java.io.*;
public class A{

    HashMap<String,String> hm;
    public A(){
        hm=new HashMap<String,String>();

        hm.put("1","A");
        hm.put("2","B");
        hm.put("3","C");

        method2(hm);

    }

public void method2(HashMap<String,String> map) {
    //write to file : "fileone"
    try {
        File fileTwo=new File("filetwo.txt");
        FileOutputStream fos=new FileOutputStream(fileTwo);
        PrintWriter pw=new PrintWriter(fos);

        for(Map.Entry<String,String> m :map.entrySet()){
            pw.println(m.getKey()+"="+m.getValue());
        }

        pw.flush();
        pw.close();
        fos.close();
    } catch(Exception e) {}

    //read from file 
    try {
        File toRead=new File("filetwo.txt");
        FileInputStream fis=new FileInputStream(toRead);

        Scanner sc=new Scanner(fis);

        HashMap<String,String> mapInFile=new HashMap<String,String>();

        //read data from file line by line:
        String currentLine;
        while(sc.hasNextLine()) {
            currentLine=sc.nextLine();
            //now tokenize the currentLine:
            StringTokenizer st=new StringTokenizer(currentLine,"=",false);
            //put tokens ot currentLine in map
            mapInFile.put(st.nextToken(),st.nextToken());
        }
        fis.close();

        //print All data in MAP
        for(Map.Entry<String,String> m :mapInFile.entrySet()) {
            System.out.println(m.getKey()+" : "+m.getValue());
        }
    }catch(Exception e) {}
  }

public static void main(String args[]) {
        new A();
}

}

注意:上面的代码可能不是完成这项任务的最快方法,但我想展示一些类的应用

ObjectOutputStreamObjectInputStreamHashMapSerializableStringTokenizer

【讨论】:

    【解决方案2】:

    我能想到的最简单的解决方案是使用 Properties 类。

    保存地图:

    Map<String, String> ldapContent = new HashMap<String, String>();
    Properties properties = new Properties();
    
    for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
        properties.put(entry.getKey(), entry.getValue());
    }
    
    properties.store(new FileOutputStream("data.properties"), null);
    

    加载地图:

    Map<String, String> ldapContent = new HashMap<String, String>();
    Properties properties = new Properties();
    properties.load(new FileInputStream("data.properties"));
    
    for (String key : properties.stringPropertyNames()) {
       ldapContent.put(key, properties.get(key).toString());
    }
    

    编辑:

    如果您的地图包含纯文本值,则在您通过任何文本编辑器打开文件数据时它们将可见,如果您序列化地图则不是这种情况:

    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
    out.writeObject(ldapContent);
    out.close();
    

    编辑2:

    在保存示例中而不是 for 循环(如 OldCurmudgeon 所建议的):

    properties.putAll(ldapContent);
    

    但是,对于加载示例,这是可以做到的最好的:

    ldapContent = new HashMap<Object, Object>(properties);
    

    【讨论】:

    • Properties 实现Map 你应该能够使用putAll 来填充它。此外,由于 HashMap 有一个 HashMap(Map&lt;? extends K,? extends V&gt; m) 构造函数,您应该能够出于同样的原因在构造时填充它。
    • 我同意,它简化了解决方案
    • 此解决方案不维护来自 Hashmap 的顺序。是否可以从在地图中维护插入顺序的 TreeMap 写入文件?
    【解决方案3】:

    HashMap 实现了Serializable,因此您可以使用正常的序列化将 hashmap 写入文件

    这是Java - Serialization 示例的链接

    【讨论】:

    • 完美。它有效 :D 非常感谢!!!
    【解决方案4】:

    您可以使用 ObjectOutputStream 中的writeObject 将对象写入文件

    ObjectOutputStream

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多