Programming Tips - Java: read and parse a CSV file

Date: 2019dec10
Language: Java

Q.  Java: read and parse a CSV file

A.  line.split(",") doesn't work since you can have commas inside quotes.

public class Csv { // Handles: // - Quoted cells // - Backslashed chars // - Regular cells (of course) public static ArrayList<String> parseLine(final String csvLine) { ArrayList<String> a = new ArrayList<String>(); boolean inQuote = false; boolean inBackslash = false; String cell = ""; for (int i = 0; i < csvLine.length(); i++) { final char c = csvLine.charAt(i); if (inQuote) { if (c == '"') { inQuote = false; continue; } cell += c; } else if (inBackslash) { cell += c; inBackslash = false; } else { switch(c) { case '"': inQuote = true; break; case '\\': inBackslash = true; break; case ',': a.add(cell); cell = ""; break; default: cell += c; } } } if (!cell.isEmpty()) { a.add(cell); } return a; } }
This is very straight forward. Not especially clever. But it works for me.