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

后端 未结 3 1083
粉色の甜心
粉色の甜心 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:32

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

    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 map = new HashMap();
    
        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();
    }
    

提交回复
热议问题