gpt4 book ai didi

Java读取txt文件到hashmap,按 ":"分割

转载 作者:行者123 更新时间:2023-12-02 08:44:32 30 4
gpt4 key购买 nike

我有一个 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(它有一些微妙的行为,恕我直言,实际上麻烦大于其值(value))。

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读取txt文件到hashmap,按 ":"分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29061782/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com