Java将txt文件读取到hashmap中,并用“:”分隔


问题内容

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