简体   繁体   中英

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?

By default, first record read by CSVParser will always be a header record, eg 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.

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.

In Kotlin:

val reader = File(path).bufferedReader()
val records = CSVFormat.DEFAULT.withFirstRecordAsHeader()
    .withIgnoreHeaderCase()
    .withTrim()
    .parse(reader)

println(records.headerNames)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM