Get CSV file header using apache commons

By default, first record read by CSVParser will always be a header record, e.g. in the below example:

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

csvRecords.get(0) will return the header record.


I looked everywhere and even the solution above didn't work. For anyone else with this issue, this does.

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

Note that your use of .next() has consumed one row of the CSV.


Since Apache Commons CSV v1.9.0, the withSkipHeaderRecord() & the withFirstRecordAsHeader() methods are deprecated. A builder interface is provided. Use it thusly:

CSVFormat.DEFAULT.builder()
    .setHeader()
    .setSkipHeaderRecord(true)
    .build();

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

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

List<String> headers = parser.getHeaderNames();

This worked for me. The last line is what you need, extracts the headers found by the parser into a List of Strings.