19

私はHashMap2つの文字列を持つを持っていMap<String, String> ldapContent = new HashMap<String, String>ます。

次にMap、を外部ファイルに保存して、Map後で初期化せずに使用できるようにします...

Mapでは、後でもう一度使用するには、をどのように保存する必要がありますか?

4

4 に答える 4

49

私が考えることができる最も簡単な解決策は、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);
于 2012-10-05T14:09:14.840 に答える
22

インターフェイスをHashMap実装しているため、クラスを使用して全体をファイルに書き込み、クラスを使用 して再度読み取ることができます。SerializableObjectOutputStreamMapObjectInputStream

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

}

または、データをテキストとしてファイルに書き込みたい場合は、Mapキーと値を1行ずつ繰り返して書き込み、1行ずつもう一度読み取ってに追加するだけです。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を参照してください

于 2012-10-05T14:23:14.757 に答える
21

HashMapSerializable通常のシリアル化を使用してハッシュマップをファイルに書き込むことができるように実装します

これがJavaのリンクです-シリアル化の例

于 2012-10-05T14:04:04.530 に答える
2

writeObjectObjectOutputStreamを使用して、オブジェクトをファイルに書き込むことができます。

ObjectOutputStream

于 2012-10-05T14:05:09.973 に答える