Home > other >  Optional fields in CSV parser
Optional fields in CSV parser

Time:07-02

I am writing code to read a CSV file.

A, B, C
1, 1, 1
2, 2, 2

Sometimes column C will be present, and sometimes it will not be. If it's not, I really don't care, but if it is I want to handle it. I'm also using the Univocity parsers, but don't necessarily have to.

CsvParserSettings settings = new CsvParserSettings();
settings.getFormat().setLineSeparator("\n");
settings.setHeaderExtractionEnabled(true);

CsvParser parser = new CsvParser(settings);
parser.beginParsing(file);

Record record;
parser.getRecordMetadata();

while ((record = parser.parseNextRecord()) != null) {
   String a = record.getString("A");
   long b = record.getLong("B");
   long c = record.getLong("C");
}

I can do something like

long c = 1;
try{
  c = record.getLong("C");
} catch (Exception e) {}

But this seems needlessly complex. Is there some kind of setting that makes a field entirely optional?

CodePudding user response:

Record contains a getValues() method that returns all values. You could use this to check the number of values to avoid an exception.

if( record.getValues().length > 2 )
  long c = record.getLong("C");

Untested, I just glanced at the API docs.

(The Apache CSV parser has a CSVRecord with a size() method you can test directly, with less (I assume) overhead. In case you might be interested in switching.)

CodePudding user response:

Maybe you could use the isMapped method from CSVrecord

if(record.isMapped("C")){
 c = record.getLong("C");
} else ...
  • Related