javacsvapache-commons-csv

Get CSV file header using apache commons


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?


Solution

  • 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.