使用apache commons获取CSV文件头

use*_*344 7 java csv apache-commons-csv

我一直在寻找过去2个小时来解决我的问题是徒劳的.我试图使用Apache commons读取CSV文件,我能够读取整个文件但我的问题是如何只提取数组中CSV的标题?

Dar*_*hta 7

默认情况下,读取的第一个记录CSVParser将始终是标题记录,例如在下面的示例中:

CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);
FileReader fileReader = new FileReader("file");
CSVParser csvFileParser = new CSVParser(fileReader, csvFileFormat);
List csvRecords = csvFileParser.getRecords();
Run Code Online (Sandbox Code Playgroud)

csvRecords.get(0) 将返回标题记录.

  • 这是一个不可能的答案。它似乎是从 https://examples.javacodegeeks.com/core-java/apache/commons/csv-commons/writeread-csv-files-with-apache-commons-csv-example/ 抄袭的。请注意,“FILE_HEADER_MAPPING”包含标头..这就是原始问题所要求的。 (2认同)

小智 7

我到处寻找,甚至上面的解决方案也不起作用。对于有此问题的其他人,确实如此。

Iterable<CSVRecord> records;
Reader in = new FileReader(fileLocation);
records = CSVFormat.EXCEL.withHeader().withSkipHeaderRecord(false).parse(in);
Set<String> headers = records.iterator().next().toMap().keySet();
Run Code Online (Sandbox Code Playgroud)

请注意,您的使用.next()消耗了 CSV 的一行。


Jus*_*lin 6

BufferedReader br = new BufferedReader(new FileReader(filename));

CSVParser parser = CSVParser.parse(br, CSVFormat.EXCEL.withFirstRecordAsHeader());

List<String> headers = parser.getHeaderNames();
Run Code Online (Sandbox Code Playgroud)

这对我有用。最后一行是您需要的,将解析器找到的标头提取到字符串列表中。


Lav*_*bey 6

自 Apache Commons CSV v1.9.0 起,withSkipHeaderRecord()&withFirstRecordAsHeader()方法已被弃用。提供了构建器接口。如此使用它:

CSVFormat.DEFAULT.builder()
    .setHeader()
    .setSkipHeaderRecord(true)
    .build();
Run Code Online (Sandbox Code Playgroud)