Skip to content

Instantly share code, notes, and snippets.

@benjbaron
Created July 10, 2015 08:33
Show Gist options
  • Save benjbaron/898971351936c53568a6 to your computer and use it in GitHub Desktop.
Save benjbaron/898971351936c53568a6 to your computer and use it in GitHub Desktop.
Read CSV with a header
public static ArrayList<Map<String, String>> readCSV(String filePath) throws IOException {
InputStream is = new FileInputStream(filePath);
ArrayList<Map<String, String>> al = new ArrayList<Map<String, String>>();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String[] headerLine = br.readLine().split(","); // reads the header of the file
String line = br.readLine(); // reads the first line of data
while (line != null) {
String[] values = line.split(",");
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < values.length; i++) {
map.put(headerLine[i], values[i]); // maps the header with corresponding value
}
al.add(map); // adds the map to the ArrayList
line = br.readLine();
}
br.close();
return al;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment