OpenCSV is a java library for reading and writing CSV files. I want to read a CSV file and extract the header of the CSV file before handling the data records. How to do this?
This is my current code and where I need the header information:
BufferedReader in = new BufferedReader(new InputStreamReader(file.getInputStream()));
CSVParser csvParser = new CSVParserBuilder().withSeparator('\t').build();
CSVReader csvReader = new CSVReaderBuilder(in).withCSVParser(csvParser).build();
// The code that follows depends on the column names, so
// I want to get the header information here so I can
// discover if I have to map to the Book entity class or to another one.
CsvToBean<Book> csvToBeanConverter = new CsvToBeanBuilder<Book>(csvReader).withType(Book.class).build();
Iterator<Book> bookIter = csvToBeanConverter.iterator();
bookIter.forEachRemaining(book -> {
System.out.println("book: " + book);
});
UPDATE 1:
I start to think that the two "standard" solutions OpenCSV and apache-commons-csv both have their weaknesses, so feel free to tell me your favorite CSV libraries. Put them into comments, not answers, because it's opinionated information by definition.
UPDATE 2:
How to read CSV headers and get them in to a list in java is only a workaround-grade solution for this question, because for making it work together with CsvToBean
it involves mark()
and reset()
on the BufferedReader
and therefor it limits the possible header size, throwing an exception if exceeded. See my answer for for details.