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

后端 未结 3 1055
粉色の甜心
粉色の甜心 2020-12-15 15:09

I have a txt file with the form:

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

I want to put all the keys with their value in a hashMap that I\'ve crea

3条回答
  •  执笔经年
    2020-12-15 15:35

    The below will work in 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.

    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.

    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 mapFromFile = Files.lines(path)
                .filter(s -> s.matches("^\\w+:\\w+"))
                .collect(Collectors.toMap(k -> k.split(":")[0], v -> v.split(":")[1]));
        }
    }
    

提交回复
热议问题