I have a CSV file that contains 3 headers A, B, C. In my code I use CSVReader's get method to access the values in these headers. Is there a way I can CSVFormat to avoid a get() IllegalArgumentException if I use the same code to process a file with only headers A, B (and not C)?
Thanks.
I think you can just use the "Header auto detection" and read column "C" only if it is detect as header via getHeaderMap():
try (Reader in = new StringReader(
"A,B,C\n" +
"1,2,3\n")) {
CSVParser records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(in);
for (CSVRecord record : records) {
System.out.println("A: " + record.get("A"));
System.out.println("B: " + record.get("B"));
System.out.println("C: " + record.get("C"));
}
}
try (Reader in = new StringReader(
"A,B\n" +
"4,5\n")) {
CSVParser records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(in);
for (CSVRecord record : records) {
System.out.println("A: " + record.get("A"));
System.out.println("B: " + record.get("B"));
if(records.getHeaderMap().containsKey("C")) {
System.out.println("C: " + record.get("C"));
} else {
System.out.println("C not found");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With