if a CSV file contains three columns and if the values are as given below
a,b,c
//empty line
,,,
a,b,c
There are two valid records. Using Apache commons CSV parser, i could easily skip the record which has empty lines. But when the records contain only null values, how to skip it then?
To overcome this, I'm using String equals() with already constructed empty record. Here is a sample implementation.
List<String[]> csvContentsList = new ArrayList<String[]>();
CSVFormat csvFormat = CSVFormat.DEFAULT.withNullString("");
CSVParser csvParser = new CSVParser(fileReader, csvFormat);
String[] nullRecordArray = { null, null, null};
String nullRecordString = Arrays.toString(nullRecordArray);
for (CSVRecord csvRecord : csvParser) {
try {
String values[] = { csvRecord.get(0),csvRecord.get(1),csvRecord.get(2) };
if (!nullRecordString.equals(Arrays.toString(values))) //lineA
csvContentsList.add(values);
} catch (Exception e) {
// exception handling
}
}
When i don't use the line marked as 'lineA', this implementation gives three records in the csvContentsList as below
[a,b,c]
[null,null,null]
[a,b,c]
Is there any inbuilt way to do this? or any other better way?