Java – Read from a Text File into a hash map or list


Possible Duplicate:
String parsing in Java with delimeter tab “\t” using split

How do I read strings from a text file and store in a hashmap? File contains two columns.

File is like:

Title en_CA

1 In accordance with the Statutory Conditions of your policy, we must advise that coverage under your policy will cease to be in effect 12:01 a.m., 15 days following receipt of this letter at the post office to which it is addressed.

The columns (like Title and en_CA or 1 and In accordance…) are separated by a tab not a space.


Best Solution

This should get you started. You'll want to do some checking along the way to make sure each line actually has two parts and probably wrap the code in some try/catch blocks. I'm assuming you want the first column to be the key and the second column to be the value.

public class ReadToHashmap {
    public static void main(String[] args) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        BufferedReader in = new BufferedReader(new FileReader(""));
        String line = "";
        while ((line = in.readLine()) != null) {
            String parts[] = line.split("\t");
            map.put(parts[0], parts[1]);


title   en_CA
1       In accordance blah bla blah


{1=In accordance blah bla blah, title=en_CA}