How to differentiate between empty string and null with OpenCSV
It is not possible. There is no difference between an empty string and the java specific null
in the CSV
format's philosophy. The null
is an empty reference in the java
object memory model. In CSV there aren't any references, but only empty values.
I found the solution: strictQuotes can be used to get nulls:
CSVReader reader = new CSVReader(isReader, ',', '"', true);
while ((col = reader.readNext()) != null) {
String c1 = col[1];
if (null != c1) {
// ...
}
}
with open csv 5.0
CSVParser csvParser = new CSVParserBuilder()
.withSeparator(",")
.withQuoteChar('"')
.withFieldAsNull(CSVReaderNullFieldIndicator.BOTH)
.build();
csvReader = new CSVReaderBuilder(new InputStreamReader(...))
.withCSVParser(csvParser)
.build();
Adding to @Gavriel's answer, starting from OpenCSV 3.6 (maybe earlier), I found that strictQuotes doesn't help with returning null anymore.
CSVReaderBuilder has withFieldAsNull() for this purpose.
CSVReader csvReader = new CSVReaderBuilder(csvFileReader)
.withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS)
.build();