Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 958
tribbloid Avatar asked Mar 11 '16 19:03

tribbloid


1 Answers

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());
like image 136
Sven Schoenung Avatar answered Oct 25 '22 00:10

Sven Schoenung