How to differentiate between empty string and null with OpenCSV

久未见 提交于 2019-12-23 11:45:08

问题


This is my code:

CSVReader reader = new CSVReader(isReader);
while ((col = reader.readNext()) != null) {
   String c1 = col[1];
}

this is my csv file:

"a","","c"
"1",,"3"

Is there a way I can differentiate between null and ""? OpenCSV seems to treat everything as non-null String. Can I tell it to treat empty fields as null?


回答1:


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.




回答2:


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) {
       // ...
   }
}



回答3:


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();


来源:https://stackoverflow.com/questions/25301620/how-to-differentiate-between-empty-string-and-null-with-opencsv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!