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

14 java dictionary file hashmap

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

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

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

lin*_*ski 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);
Run Code Online (Sandbox Code Playgroud)

加载地图:

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());
}
Run Code Online (Sandbox Code Playgroud)

编辑:

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

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();
Run Code Online (Sandbox Code Playgroud)

EDIT2:

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

properties.putAll(ldapContent);
Run Code Online (Sandbox Code Playgroud)

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

ldapContent = new HashMap<Object, Object>(properties);
Run Code Online (Sandbox Code Playgroud)

  • 当`Properties`实现`Map`时,你应该可以使用`putAll`来填充它.此外,由于`HashMap`有一个`HashMap(Map <?extends K,?extends V> m)`构造函数,你应该能够在构造中填充它,原因相同. (2认同)

Far*_*baz 18

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

下面简单的代码解释ObjectOutStream和的用法ObjectInputStream

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();
}

}
Run Code Online (Sandbox Code Playgroud)

或者如果你想将数据作为文本写入文件,你可以简单地迭代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();
}

}
Run Code Online (Sandbox Code Playgroud)

注意:上面的代码可能不是执行此任务的最快方法,但我想展示一些类的应用程序

请参见ObjectOutputStream,ObjectInputStream,HashMap,Serializable,StringTokenizer


Ami*_*nde 16

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

以下是Java - Serialization示例的链接