-3

次の形式の値を含むテキスト ファイルがあります。


[id1] text1

[id2] text2

...

このテキスト ファイルを読み込んで Java のハッシュマップに書き込む方法を教えてもらえないだろうかと思っていました。任意のポインタをいただければ幸いです。

編集:はい。まだ試していません。これまでのところ、ファイルから条件を読み取ってテキスト ファイルに出力することができました。私はちょうどポインタを見ていました。ありがとう。

4

2 に答える 2

0

テキスト ファイルがオブジェクト (ハッシュマップなど) に保存できるほど小さい場合は、保存できます。または、他の解決策を考える必要があります。たとえば、20GiB のテキスト ファイルがあるとします。

読んだ行を次のように分割できます。

String[] arr = line.split("(?<=])\\s+", 2)

次に、それを HashMap (たとえば、yourMap) に入れます。

yourMap.put(arr[0], arr[1])

ここに小さな例を作りました:

final String a = "[001] text here";
    final String b = "[001] text [tricky] here";
    final String c = "[0 0 1] text here";

    final String regex = "(?<=])\\s+";

    // if you want to test it, you would see key/value are correctly splited
    System.out.println(Arrays.toString(a.split(regex, 2)));
    System.out.println(Arrays.toString(b.split(regex, 2)));
    System.out.println(Arrays.toString(c.split(regex, 2)));

//--------------------------------------    

//here is the part to put them into your file
    HashMap<String,String> yourMap = new HashMap<String,String>();
    String[] array = null;
    //for each line from that file {
    array = line.split(regex,2);
    yourMap.put(array[0], array[1]);
    //}for loop ends
于 2013-02-04T00:16:38.850 に答える
0

各行を読み取り、次のような正規表現を使用できます。

"\\[(.*?)\\]\\s*(.*)"

次に、最初のグループに ID が含まれ、2 番目のグループに値が含まれます。

まだ実際に何も試していないため、コードを提供するつもりはありませんが、PatternクラスとMatcherクラスを調べることができます。(これら 2 つのクラス名はリンクです)

正規表現の説明:

\\[   - open bracket (escaped)
(.*?) - capturing stuff inside the brackets
\\]   - close bracket
\\s*  - whitespace
(.*)  - everything after that (the data)
于 2013-02-03T23:39:34.107 に答える