How can I skip the first line of a csv in Java?
You can skip the first record using stream:
List<CSVRecord> noHeadersLine = records.stream.skip(1).collect(toList());
In version 1.9.0 of org.apache.commons:commons-csv use:
val format = CSVFormat.Builder.create(CSVFormat.DEFAULT)
.setHeader()
.setSkipHeaderRecord(true)
.build()
val parser = CSVParser.parse(reader, format)
The correct way to skip the first line if it is a header is by using a different CSVFormat
CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';').withFirstRecordAsHeader();
Update: June 30 2022
For 1.9+, use
CSVFormat.DEFAULT.builder()
.setDelimiter(';')
.setHeader()
.setSkipHeaderRecord(true) // skip header
.build();
You may want to read the first line, before passing the reader to the CSVParser
:
static void processFile(final File file) {
FileReader filereader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(filereader);
bufferedReader.readLine();// try-catch omitted
final CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';');
CSVParser parser = new CSVParser(bufferedReader, format);
final List<CSVRecord> records = parser.getRecords();
//stuff
}