Honestly, I could only find one reference to using CSVParser () , as you showed in your code example, and it was somewhere in some small blog. I think this is a mistake, but it would not hurt to ask the author for clarification. As I understand it, you tried the code without success, and therefore it looks like a tombstone to the possibility that this is actually an incorrect example of using the CSVParser.parser () method. I have never tried an example, so I canโt judge it anyway, I can just express my opinion.
To me personally, for what is needed to analyze a CSV file, I would create my own method, but if you insist on using Apache Commons CSVParser (which is well tested and verified by reliable code), then use the FilerReader version of the CSVParser.parser () method.
If the CSV file you are trying to parse is a standard comma separated (RFC4180), you can simply use the BufferReader as well as the String.split () method to parse the data on each line of the file, something like what is shown in this full executable java version. Pay attention to the readCSV () method:
package csv.parser; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class CSVParser { public static void main(String[] args) { try { List list = readCSV("MyCSVFile.csv"); // Display the list contents to console output. for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } public static List readCSV(String csvFilePath, boolean... ignoreHeader) throws FileNotFoundException, IOException { boolean useHeader = true; if (ignoreHeader.length != 0) { useHeader = ignoreHeader[0]; } List list = new ArrayList<>(); BufferedReader br = new BufferedReader(new FileReader(csvFilePath)); // Reading header. Ignoring the contents if false was supplied to ingnoreHeader. String line = br.readLine(); String[] fieldTitles = {}; if (useHeader) { fieldTitles = line.split(","); } while ((line = br.readLine()) != null) { if (!line.trim().isEmpty()) { String[] fields = line.split(","); String strg = ""; for (int i = 0; i < fields.length; i++) { if (useHeader) { if (strg.equals("")) { strg = fieldTitles[i] + ": " + fields[i]; } else { strg+= " | " + fieldTitles[i] + ": " + fields[i]; } } else { if (strg.equals("")) { strg = "Field " + (i+1) + ": " + fields[i]; } else { strg+= " | Field " + (i+1) + ": " + fields[i]; } } } list.add(strg); } } br.close(); return list; } }
Format the incoming string data, as you see, within the readCSV () method. A simple CSV text file named MyCSVFile.csv will contain the following:
NAME,CAPITAL,CURRENCY India,New Delhi,INR USA,Washington,USD England,London,GBP Japan,Tokyo,JPY
If the first line of the file, of course, will be the data header.