Get CSV file header using apache commons

user3382344 picture user3382344 · Mar 28, 2016 · Viewed 16.8k times · Source

I have been looking for the past 2 hours for a solution to my problem in vain. I'am trying to read a CSV File using Apache commons ,I am able to read the whole file but my problem is how to extract only the header of the CSV in an array?

Answer

Darshan Mehta picture Darshan Mehta · Mar 28, 2016

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.