2

I am attempting to read a CSV file then create a new object based on that CSV file. I can successfully do that with the SuperCSV library, but if an error occurs (such as a specific cell is null) it throws an error (as expected). I'm trying to gather all the errors in an ArrayList, but right now upon the first exception everything will stop. How would I get the SuperCSV CsvBeanReader to continue to the next row, even if there is an error with the processor? I have the loop condition inside the try/ catch block. Code below:

ArrayList<Duplicate> duplicates = new ArrayList<Duplicate>();
ArrayList<BadProperty> invalidProperties = new ArrayList<BadProperty>();

File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();

ICsvBeanReader beanReader = null;
try {
    beanReader = new CsvBeanReader(new FileReader(convFile), CsvPreference.STANDARD_PREFERENCE);

    final String[] header = beanReader.getHeader(true);
    final CellProcessor[] processors = getProcessors();

    Property property;
    while ((property = beanReader.read(Property.class, header, processors)) != null) {
            // logic in here


        }
    }
    catch(SuperCsvException e) {
        invalidProperties.add(new BadProperty(e.getCsvContext()));
        System.out.println(e);

    }
    finally {
        if( beanReader != null ) {
            beanReader.close();
        }
    }
Drakee510
  • 480
  • 1
  • 5
  • 15

1 Answers1

3

The most important thing is to move the try catch inside the loop, so the loop does not stop when an Exception occurs. Here is how I would do it

private void readProperties()
{
  try
  {
    beanReader = new CsvBeanReader(new FileReader(convFile), CsvPreference.STANDARD_PREFERENCE);

    while (readNextProperty())
    {
    }
  }
  catch (Exception e)
  {   
  }
  finally
  {
    if(beanReader != null)
    {
      beanReader.close();
    }
  }
}

/** Returns true when there are more properties to read. */
private boolean readNextProperty()
{
  try
  {
    Property property = beanReader.read(Property.class, header, processors);
    if (property == null)
    {
      return false;
    }

    // logic in here

  }
  catch (SuperCsvException e)
  {
    invalidProperties.add(new BadProperty(e.getCsvContext()));
    System.out.println(e);
  }

  return true;
}
Florian S.
  • 386
  • 1
  • 12