Thomas Mwania
Thomas Mwania

Reputation: 405

How to skip empty records CSVFormat parser

I am required in this set of code to parse a csv file given the URL. The problem is that some times, the file will have empty lines appended at the end of the file(I currently have no control on the file being parsed). The solution here is to ignore lines where all values are not provided when parsing the file

Here is some sample data:

HEADER1,HEADER2,HEADER13,HEADER4,HEADER5,HEADER6
1,tt,9/2/2019,12000,4116,2307306
2,tt1,9/2/2019,12000,4147,1137039
,,,,,,
,,,,,,

I have tried the following solution without success

Iterable<CSVRecord> csvRecords = CSVFormat.EXCEL.withFirstRecordAsHeader().withIgnoreEmptyLines(true).parse(new FileReader(url));

In this case, the expected result would be to get the first two lines after the header and ignore the last two lines

Upvotes: 0

Views: 796

Answers (1)

Sambit
Sambit

Reputation: 8011

You can try with the below code and check whether it works.

Iterable<CSVRecord> csvRecords = CSVFormat.EXCEL.withFirstRecordAsHeader().withIgnoreEmptyLines(true).withTrim().parse(new FileReader(url));

I have added a method .withTrim().

If it still does not work, you can check each CSVRecord as null or not inside for loop.

Upvotes: 1

Related Questions