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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29061782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:17:55  来源:igfitidea点击:

Java read txt file to hashmap, split by ":"

javafiletextjava.util.scanner

提问by Casper TL

I have a txt file with the form:

我有一个格式为 txt 的文件:

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

I want to put all the keys with their value in a hashMap that I've created. How do I get a FileReader(file)or Scanner(file)to know when to split up the keys and values at the colon (:) ? :-)

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

I've tried:

我试过了:

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

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

采纳答案by trooper

Read your file line-by-line using a BufferedReader, and for each line perform a spliton the first occurrence of :within the line (and if there is no :then we ignore that line).

使用 a 逐行读取您的文件BufferedReader,并对每一行在该行内split第一次出现时执行 a :(如果没有,:则我们忽略该行)。

Here is some example code - it avoids the use of Scanner (which has some subtle behaviors and imho is actually more trouble than its worth).

这是一些示例代码 - 它避免使用 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();
}

回答by beresfordt

The below will work in java 8.

下面将在 java 8 中工作。

The .filter(s -> s.matches("^\\w+:\\w+$"))will mean it only attempts to work on line in the file which are two strings separated by :, obviously fidling with this regex will change what it will allow through.

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

The .collect(Collectors.toMap(k -> k.split(":")[0], v -> v.split(":")[1]))will work on any lines which match the previous filter, split them on :then use the first part of that split as the key in a map entry, then the second part of that split as the value in the map entry.

.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]));
    }
}

回答by Oleg Mikhailov

One more JDK 1.8 implementation.

又一个 JDK 1.8 实现。

I suggest using try-with-resources and forEachiterator with putIfAbsent()method to avoid java.lang.IllegalStateException: Duplicate key valueif there are some duplicate values in the file.

我建议使用 try-with-resources 和forEachiterator with putIfAbsent()method 来避免java.lang.IllegalStateException: Duplicate key value如果文件中有一些重复值。

FileToHashMap.java

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

.txt

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

The output is:

输出是:

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