javacsvsupercsv

adding the error line in log when SuperCSV fails


I'm using SuperCSV to parse a CSV file. It works flawlessly. The CSV file I'm passing may contain some invalid records in it. At that time, is it possible to log which line is not processed?

List<InputBean> csvContentsList = new ArrayList<InputBean>();
ICsvBeanReader beanReader = new CsvBeanReader(fileReader, CsvPreference.STANDARD_PREFERENCE);
InputBean bean = null;
do {
    try {
        bean = beanReader.read(InputBean.class, header, getProcessors());
        if (bean != null)
            csvContentsList.add(bean);
    } catch (Exception e) {
        logger.error("Error in parsing the record:"+e.getMessage());
    }
} while (bean != null);

In this code, if the CSV file contains invalid record, it throws an error and it is caught in the catch block. How could be print that invalid record? or the line number of it ?


Solution

  • If there is an invalid line while processing a CSV file with beanreader.read(...) method, then documentation says that SuperCsvException is thrown from which you can ask CsvContext with method getCsvContext() and from this you can get all kinds of context information including line number. So be more specific in what you catch and handle it appropriately.

    Related documentation:

    https://super-csv.github.io/super-csv/apidocs/org/supercsv/io/ICsvBeanReader.html

    https://super-csv.github.io/super-csv/apidocs/org/supercsv/exception/SuperCsvException.html#getCsvContext--

    https://super-csv.github.io/super-csv/apidocs/org/supercsv/util/CsvContext.html