Search code examples
javacsvparsingapache-commons-csv

How to skip comments in a record


I'm using the Apache Commons CSV 1.9.0 library and to parse a csv file, the problem that I cannot set a comment marker "#" to fill the comment filed in the record so they can be skipped when looping through the file. this is the code I'm using:

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;    
Reader reader = Files.newBufferedReader((Paths.get(filename)), StandardCharsets.UTF_16LE);
CSVFormat csvFormat = CSVFormat.DEFAULT;
csvFormat.builder().setCommentMarker('#');
Iterable<CSVRecord> records = csvFormat.parse(reader);
char marker = csvFormat.getCommentMarker(); // marker is for test and it is empty.
for (CSVRecord record : records)
{
  if (record.isSet(SHEET_COLUMN_1))
  {
    // TODO
  }
}

can you please help me with this?

Kind regards, Maan


Solution

  • CSVFormat.builder() creates a new instance of builder, but you're using old instance of csvFormat.

    Use:

    CSVFormat csvFormat = CSVFormat.DEFAULT
      .builder()
      .setCommentMarker('#')
      .build();