2

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.

Thanks

Community
  • 1
  • 1
user1152660
  • 141
  • 2
  • 2
  • 4

2 Answers2

11

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("example.tab"));
        String line = "";
        while ((line = in.readLine()) != null) {
            String parts[] = line.split("\t");
            map.put(parts[0], parts[1]);
        }
        in.close();
        System.out.println(map.toString());
    }
}

Input:

title   en_CA
1       In accordance blah bla blah

Output:

{1=In accordance blah bla blah, title=en_CA}
B. Anderson
  • 3,079
  • 25
  • 33
3

You can do something like:

1) Read your file into a string

2) Use String.split("\t") method to split the content and use the count of the splits to identify a new line

3) than add those content into an arraylist or collection of your choice.

Liam
  • 2,837
  • 23
  • 36
RanRag
  • 48,359
  • 38
  • 114
  • 167