mhery mhery - 2 months ago 15
Java Question

Using Apache Commons CSV to read file starting from the second line

I have this

CSV
file that I want to read:

ID;Name;Age
GEORGE;GEORGE;19
JOHN;JOHNNY;45
MARCO;MARCO POLO;32


I also have to read it using this command:

for (CSVRecord rec : CSVFormat.DEFAULT.withDelimiter(';').parse(in)) {
//some code
}


I don't want to read the first line, because it's just the description of what contain the fields

I also tried to find the resolution of this in
stackoverflow
and other sites, but I didn't find how to do it.

I imported
CSVRecord
and
CSVFormat
from
org.apache.commons.csv.CSVFormat
and
org.apache.commons.csv.CSVRecord

Answer

See the "Working with headers" section of the user guide.

Specifically, you can configure the parser to know that the first line is a header, using CSVFormat.withFirstRowAsHeader()