How do I skip the first line of CSV in Java?
•
Java
I want to skip the first line and use the second line as the title
I am using the classes in Apache commons CSV to process CSV files
The title of the CSV file is on the second line, not the first line (including coordinates)
My code looks like this:
static void processFile(final File file) { FileReader filereader = new FileReader(file); final CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';'); CSVParser parser = new CSVParser(filereader,format); final List<CSVRecord> records = parser.getRecords(); //stuff }
I naively thought,
CSVFormat format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(;)
It will solve the problem because it is different from withfirstrowasheader. I think it will detect that the first row does not contain any semicolons instead of records It doesn't I tried to skip the first line (csvformat seems to think it's a title)
CSVFormat format = CSVFormat.DEFAULT.withSkipHeaderRecord().withFirstRecordAsHeader().withDelimiter(;);
But it won't work What can I do? What is the difference between withfirstrowasheader and withfirstrecordasheader?
Solution
Before passing the reader to the csvparser, you may need to read the first line:
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 }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码