PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 27, 2022

[FIXED] How can I skip the first line of a csv in Java?

 August 27, 2022     apache-commons-csv, csv, java     No comments   

Issue

I want to skip the first line and use the second as header.

I am using classes from apache commons csv to process a CSV file.

The header of the CSV file is in the second row, not the first (which contains 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(;)

would solve the problem, as it's different from withFirstRowAsHeader and I thought it would detect that the first row doesn't contain any semicolons and is not a record. It doesn't. I tried to skip the first line (that CSVFormat seems to think is the header) with

CSVFormat format = CSVFormat.DEFAULT.withSkipHeaderRecord().withFirstRecordAsHeader().withDelimiter(;);

but that also doesn't work. What can I do? What's the difference between withFirstRowAsHeader and withFirstRecordAsHeader?


Solution

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
}


Answered By - Arnaud
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing