Search code examples
javasupercsv

Is there a workaround for Optional ParseDate SuperCsvCellProcessorException in SuperCSV?


I'm using SuperCSV in java to read a csv file. I have a column containing dates but the records may not be populated so I set it to optional. In my CellProcessor I define the field as

    ...,
    new Optional(new ParseDate("MM/dd/yyyy",true)),
    ...

When ParseDate encounters an empty cell it returns "...SuperCsvCellProcessorException:' ' could not be parsed as a Date."

How do I continue processing the parseDate in this situation?


Solution

  • Only empty columns (i.e. empty String) are mapped to null when Super CSV reads the CSV - a space will be read as a space. This is because whitespace is meant to be important in RFC4180, the CSV mimetype specification.

    So Optional won't bypass the next processor for a space. You can use this processor setup instead:

    new Optional(new Token(" ", null, new ParseDate("MM/dd/yyyy",true)));
    

    This will return null if it encounters null (i.e. empty String in the CSV) or a single space, and bypass trying to parse it as a date.

    You could also enable the surroundingSpacesNeedQuotes preference to get around this, but just be aware that this will also strip out any leading/trailing spaces - which you might not want.