0

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 ?

RamValli
  • 4,389
  • 2
  • 33
  • 45
  • 1
    If you don't like catching exceptions, you can also implement this using a cell processor that suppresses and collects each exception. See [here](http://stackoverflow.com/questions/13646982/validate-every-field-in-a-single-pass-with-supercsv/13658467#13658467) for an example. – James Bassett Mar 14 '16 at 11:19

1 Answers1

0

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

Tarmo
  • 3,851
  • 2
  • 24
  • 41
  • Here the exception is IllegalArgumentException as the number of columns aren't matching... Anyhow thanks for the pointer. – RamValli Mar 14 '16 at 14:43