【问题标题】:Java read txt file to hashmap, split by ":"Java读取txt文件到hashmap,用“:”分割
【发布时间】:2015-03-15 14:32:02
【问题描述】:

我有一个 txt 文件,格式如下:

Key:value
Key:value
Key:value
...

我想将所有键及其值放入我创建的 hashMap 中。如何获得 FileReader(file)Scanner(file) 以知道何时在冒号 (:) 处拆分键和值? :-)

我试过了:

Scanner scanner = new scanner(file).useDelimiter(":");
HashMap<String, String> map = new Hashmap<>();

while(scanner.hasNext()){
    map.put(scanner.next(), scanner.next());
}

【问题讨论】:

    标签: java file text java.util.scanner


    【解决方案1】:

    使用BufferedReader 逐行读取您的文件,并为每一行在第一次出现: 时执行split(如果没有:,那么我们将忽略它行)。

    这里是一些示例代码 - 它避免使用 Scanner(它有一些微妙的行为,恕我直言实际上比它的价值更麻烦)。

    public static void main( String[] args ) throws IOException
    {
        String filePath = "test.txt";
        HashMap<String, String> map = new HashMap<String, String>();
    
        String line;
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        while ((line = reader.readLine()) != null)
        {
            String[] parts = line.split(":", 2);
            if (parts.length >= 2)
            {
                String key = parts[0];
                String value = parts[1];
                map.put(key, value);
            } else {
                System.out.println("ignoring line: " + line);
            }
        }
    
        for (String key : map.keySet())
        {
            System.out.println(key + ":" + map.get(key));
        }
        reader.close();
    }
    

    【讨论】:

    • 效果如我所愿!非常感谢您的详细示例! :-)
    • 这些天关闭资源是否被高估了?似乎再也没有人这样做了。
    • 绝对高估了 这只是汤姆的一个例子,但你的观点是正确的。如果您认为值得,请随时修改答案以添加尝试/最终。
    【解决方案2】:

    以下将在 java 8 中工作。

    .filter(s -&gt; s.matches("^\\w+:\\w+$")) 意味着它只尝试在文件中在线工作,这是由: 分隔的两个字符串,显然摆弄这个正则表达式会改变它允许通过的内容。

    .collect(Collectors.toMap(k -&gt; k.split(":")[0], v -&gt; v.split(":")[1])) 将适用于与前一个过滤器匹配的任何行,将它们拆分为 :,然后使用该拆分的第一部分作为映射条目中的键,然后将该拆分的第二部分作为值在地图条目中。

    import java.io.IOException;
    import java.nio.file.FileSystems;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class Foo {
    
        public static void main(String[] args) throws IOException {
            String filePath = "src/main/resources/somefile.txt";
    
            Path path = FileSystems.getDefault().getPath(filePath);
            Map<String, String> mapFromFile = Files.lines(path)
                .filter(s -> s.matches("^\\w+:\\w+"))
                .collect(Collectors.toMap(k -> k.split(":")[0], v -> v.split(":")[1]));
        }
    }
    

    【讨论】:

    • 或者,可以使用Files.lines(Paths.get(filePath))...
    【解决方案3】:

    另一个 JDK 1.8 实现。

    如果文件中有一些重复值,我建议使用 try-with-resources 和 forEach 迭代器和 putIfAbsent() 方法来避免 java.lang.IllegalStateException: Duplicate key value

    FileToHashMap.java

    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.stream.Stream;
    
    public class FileToHashMap {
        public static void main(String[] args) throws IOException {
            String delimiter = ":";
            Map<String, String> map = new HashMap<>();
    
            try(Stream<String> lines = Files.lines(Paths.get("in.txt"))){
                lines.filter(line -> line.contains(delimiter)).forEach(
                    line -> map.putIfAbsent(line.split(delimiter)[0], line.split(delimiter)[1])
                );
            }
    
            System.out.println(map);    
        }
    }
    

    in.txt

    Key1:value 1
    Key1:duplicate key
    Key2:value 2
    Key3:value 3
    

    输出是:

    {Key1=value 1, Key2=value 2, Key3=value 3}
    

    【讨论】:

      【解决方案4】:

      我会这样做

      Properties properties = new Properties();
      properties.load(new FileInputStream(Path of the File));
      for (Map.Entry<Object, Object> entry : properties.entrySet()) {
          myMap.put((String) entry.getKey(), (String) entry.getValue());
      }
      

      【讨论】:

      • 请提供一些解释。
      猜你喜欢
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多