1

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?

gregmacfarlane
  • 2,121
  • 3
  • 24
  • 53
  • As a note, this question is precisely the opposite of [this one](https://stackoverflow.com/q/56792683/843419) – gregmacfarlane Jul 01 '22 at 22:56
  • Is your `Record` the same as [CSVRecord?](https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVRecord.html) I want to make sure I understand what API is being used. – markspace Jul 01 '22 at 23:08
  • Sorry, I'm using the univocity parsers, `com.univocity.parsers.common.record.Record`. Will edit question. – gregmacfarlane Jul 01 '22 at 23:14

2 Answers2

1

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.)

markspace
  • 10,621
  • 3
  • 25
  • 39
  • This is a good idea, but in my use case I can also imagine that there might be additional columns that I want to ignore. Thus there might be three columns, `[A, B, D]` and I want to just get the values of A and B – gregmacfarlane Jul 01 '22 at 23:25
  • It would result in a cascade of `if` checks, sure. You might be able to improve things with a method call to encapsulate some of the over head. – markspace Jul 01 '22 at 23:26
0

Maybe you could use the isMapped method from CSVrecord

if(record.isMapped("C")){
 c = record.getLong("C");
} else ...
Csisanyi
  • 669
  • 4
  • 16