繁体   English   中英

Java读取txt文件到hashmap,用“:”分割

[英]Java read txt file to hashmap, split by “:”

我有一个格式为 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());
}

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

下面将在 java 8 中工作。

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

.collect(Collectors.toMap(k -> k.split(":")[0], v -> 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]));
    }
}

又一个 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);    
    }
}

.txt

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

输出是:

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

我会这样做

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM