【问题标题】:Text file to a hashmap文本文件到哈希图
【发布时间】:2013-01-18 16:09:15
【问题描述】:

我有一个文本文件,其值的格式为:


[id1] text1

[id2] text2

...

我想知道是否有人可以告诉我如何读取这个文本文件并将其写入 java 中的 hashmap。任何指针表示赞赏。

编辑:是的。我还没试过。到目前为止,我刚刚能够从文件中读取条款并将其打印在文本文件中。我只是在看指针。谢谢。

【问题讨论】:

  • 两个问题,a) 你的文件有多大? b) 你尝试了什么?向我们展示您的代码
  • @TomášZato:我建议只用谷歌搜索它。您会从 Google 获得比您希望在 StackOverflow 评论中获得更好的答案。
  • 谢谢。就像其他人想知道的那样:这是一种算法,它使用哈希原理(哈希字符串是值的地址)将数字分配给字符串,从而映射关联数组。
  • @rya11111 在你提问之前先做研究。 How to Ask

标签: java oop data-structures hashmap


【解决方案1】:

如果您的文本文件小到可以保存在对象中(例如 hashmap),您可以保存。或者您必须考虑其他解决方案。例如你有一个 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

【讨论】:

    【解决方案2】:

    您可以阅读每一行并使用正则表达式,例如:

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

    那么第一组将包含 ID,第二组将包含值。

    我不会提供代码,因为您甚至还没有真正尝试过任何东西,但是您可以查看 PatternMatcher 类。 (这两个类的名字就是链接)

    正则表达式的解释:

    \\[   - open bracket (escaped)
    (.*?) - capturing stuff inside the brackets
    \\]   - close bracket
    \\s*  - whitespace
    (.*)  - everything after that (the data)
    

    【讨论】:

    • 用限制分割就可以了,不需要正则表达式分组。在一些棘手的情况下,您的正则表达式也不安全......
    • 是的。我还没试过。到目前为止,我刚刚能够从文件中读取条款并将其打印在文本文件中。我只是在看指针。谢谢。
    • @rya11111 在你提问之前先做研究。 How to Ask
    • 我确实做了一些不成功..对不起:(
    • @Kent 在什么情况下不安全?
    猜你喜欢
    • 1970-01-01
    • 2020-10-28
    • 2019-02-19
    • 2013-12-05
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2013-03-06
    • 2017-05-29
    相关资源
    最近更新 更多