Java将txt文件读取到哈希图,并以“:"分隔 [英] Java read txt file to hashmap, split by ":"

查看:91
本文介绍了Java将txt文件读取到哈希图,并以“:"分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a txt file with the form:

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

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

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 (:) ? :-)

我尝试过:

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

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

推荐答案

使用BufferedReader逐行读取文件,并针对每行在:中第一次出现的位置执行split.行(如果没有:,则我们忽略该行).

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

下面是一些示例代码-避免使用Scanner(它具有一些细微的行为,恕我直言,实际上比其价值更大的麻烦).

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).

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文件读取到哈希图,并以“:"分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆