Newbie Newbie - 5 months ago 117
Java Question

Convert CSV values to a HashMap key value pairs in JAVA

HI I have a csv called

. I am trying to read the csv line by line and convert the values into a hash key value pairs .
Here is the code :-

public class Example {
public static void main(String[] args) throws ParseException, IOException {
// TODO Auto-generated method stub

BufferedReader br = new BufferedReader(new FileReader("test.csv"));
String line = null;
HashMap<String,String> map = new HashMap<String, String>();

String str[] = line.split(",");
for(int i=0;i<str.length;i++){
String arr[] = str[i].split(":");
map.put(arr[0], arr[1]);

The csv file is as follows :-


When I run this code I get this error :-

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

Can anyone please help me to fix the code and find out the error in my program ?


In your String when you split it on first time only contains arr[0] as 1 nothing in arr[1] so it will cause an Exception

If you does not need the 1,2, etc.. You can look the following code:

        String str[] = line.split(",");
        for(int i=1;i<str.length;i++){
            String arr[] = str[i].split(":");
            map.put(arr[0], arr[1]);