如何使用HashMap编写和读取文件?

时间:2012-10-05 14:01:56

标签: java file dictionary hashmap

我有一个HashMap,其中包含两个字符串Map<String, String> ldapContent = new HashMap<String, String>

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

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

4 个答案:

答案 0 :(得分:36)

我能想到的最简单的解决方案是使用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();

EDIT2:

代替for循环(由OldCurmudgeon建议)在保存示例中:

properties.putAll(ldapContent);

然而,对于加载示例,这是最好的:

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

答案 1 :(得分:17)

由于HashMap实现了Serializable接口,您只需使用ObjectOutputStream类将整个Map写入文件,然后使用ObjectInputStream类<再次读取它/ p>

下面的简单代码解释了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 :(得分:16)

HashMap实现Serializable,因此您可以使用普通序列化将hashmap写入文件

以下是Java - Serialization示例

的链接

答案 3 :(得分:2)

您可以使用ObjectOutputStream

中的writeObject将对象写入文件

ObjectOutputStream