为什么Apache Commons CSVParser.getHeaderMap()总是返回null?

7
当使用Apache Commons CSV读取以下TSV片段时:
Name    DOB SIN Address, contact information
"Patience Middleton"    "18-4-87"   720463771   "varius Cras sem aliquam taciti fames hendrerit tempor"

这是我的代码:

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

然而,我总是会得到一个NullPointerException,指出parsed.getHeaderMap() == null。根据API(https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVParser.html),该方法可能返回按列顺序迭代的头映射的副本。我的代码或CSV文件有什么问题吗?库失败了吗?
1个回答

17

默认情况下,CSVParser 假定没有标题行,并将第一行解析为常规数据。您需要显式告诉它,您希望 CSV 文件的第一行被解释为标题,通过在 CSVFormat 上调用 withHeader() 来实现:

CSVParser parsed = CSVParser.parse(csvData, 
   CSVFormat.newFormat('\t').withQuote('"').withHeader());

2
非常感谢!我在 withHeader() 函数中看到很多参数,天真地认为它们仅用于手动设置标头。 - tribbloid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接