Created
July 10, 2015 08:33
-
-
Save benjbaron/898971351936c53568a6 to your computer and use it in GitHub Desktop.
Read CSV with a header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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