Reading A Simple CSV file in java and putting it into a Map-java code

No comments
Here we are providing you a code which can be used to read a simple csv file with country code and country names, and write it ina map as key value pair.
the csv file has the country code and country name in this form-

ID,"Indonesia"
IE,"Ireland"
IL,"Israel"
IM,"Isle of Man"
IN,"India"
IO,"British Indian Ocean Territory"
IQ,"Iraq"
IR,"Iran, Islamic Republic of"
IS,"Iceland"
IT,"Italy"
JE,"Jersey"




package com.tutorialsinn.javatutorials;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CsvReader {

 private static String line = "";
 private static String cvsSplitBy = ",";

 public static Map<String, String> csvToMap(String csvFile) {

  Map<String, String> map = new HashMap<String, String>();
  BufferedReader br=null;
  try {
   br = new BufferedReader(new FileReader(csvFile));
   line = br.readLine();

  } catch (FileNotFoundException e) {

   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  while (line != null) {
   String[] splitArr = line.split(cvsSplitBy);
   map.put(splitArr[0], splitArr[1].replace("\"",""));
   try {
    line = br.readLine();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  return map;
 }
}
The code will take take a csv-file location as argument inside the static method csvToMap which will return a HashMap with keyvalue pair ,where key is the country code and value is the country name, both are string.

No comments :

Post a Comment