Why does Apache Commons CSVParser.getHeaderMap() always return null?
Asked Answered
A

1

7

When reading the following TSV snippet with Apache Commons CSV:

Name    DOB SIN Address, contact information
"Patience Middleton"    "18-4-87"   720463771   "varius Cras sem aliquam taciti fames hendrerit tempor"

This is my code:

CSVFormat format = CSVFormat.newFormat('\t').withQuote('"');
CSVParser parsed = CSVParser.parse(csvData, format);
List<CSVRecord> record = parsed.getRecords();
System.out.println(parsed.getHeaderMap().toString());

However I always get a NullPointerException stating that parsed.getHeaderMap() == null.

According to the API (https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVParser.html), the method may return a copy of the header map that iterates in column order.

Is there something wrong in my code or CSV file? Is the library failing?

Argive answered 11/3, 2016 at 19:17 Comment(0)
E
17

By default CSVParser assumes that there is no header line and parses the first line as regular data. You need to tell it explicitly that you want the first line of your CSV file to be interpreted as a header by calling withHeader() on CSVFormat:

CSVParser parsed = CSVParser.parse(csvData, 
   CSVFormat.newFormat('\t').withQuote('"').withHeader());
Erubescent answered 11/3, 2016 at 19:52 Comment(2)
Thanks a lot! I saw may parameters in withHeader() function and naively thought they are only used to manually set headers.Argive
New syntax - CSVFormat.Builder.create().setHeader()Boutin

© 2022 - 2024 — McMap. All rights reserved.