Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java read txt file to hashmap, split by ":"

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 created. How do I get a FileReader(file) or Scanner(file) to know when to split up the keys and values at the colon (:) ? :-)

I've tried:

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

while(scanner.hasNext()){
    map.put(scanner.next(), scanner.next());
}
like image 971
Casper TL Avatar asked Nov 29 '22 14:11

Casper TL


1 Answers

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<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();
}
like image 128
trooper Avatar answered Dec 05 '22 17:12

trooper