Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache commons csv skip lines

Tags:

java

csv

How to skip lines in input file with apache commons csv. In my file first few lines are garbage useful meta-information like date, etc. Can't find any options for this.

private void parse() throws Exception {
    Iterable<CSVRecord> records = CSVFormat.EXCEL
            .withQuote('"').withDelimiter(';').parse(new FileReader("example.csv"));
    for (CSVRecord csvRecord : records) {
        //do something            
    }
}
like image 776
g6380647 Avatar asked Nov 28 '15 14:11

g6380647


People also ask

How do I parse a CSV file in Apache Commons?

Parsing files Parsing files with Apache Commons CSV is relatively straight forward. The CSVFormat class provides some commonly used CSV variants: Apache Commons CSV provides several ways to access record values. The simplest way is to access values by their index in the record.

Can you skip the header line in a CSV file?

Skipping the Header Line Usually, CSV files contain headers in the first line. Hence, in most cases, it is safe to skip it and start reading from the second row. This will autodetect headers access column values:

How do I skip the first record in a CSV file?

If it does, then you are overriding this metadata with your names and you should skip the first record by calling CSVFormat.Builder.setSkipHeaderRecord (boolean) with true . You can use a format directly to parse a reader. For example, to parse an Excel file with columns header, write:

How do I use the csvparser?

Specifies the format of a CSV file and parses input. You can use one of the predefined formats: For example: The CSVParser provides static methods to parse other input types, for example: You can extend a format by calling the set methods. For example: To define the column names you want to use to access records, write:


1 Answers

Use FileReader.readLine() before starting the for-loop.

Your example:

private void parse() throws Exception {
  FileReader reader = new FileReader("example.csv");
  reader.readLine(); // Read the first/current line.

  Iterable <CSVRecord> records = CSVFormat.EXCEL.withQuote('"').withDelimiter(';').parse(reader);
  for (CSVRecord csvRecord: records) {
    // do something
  }
}
like image 118
Berendschot Avatar answered Sep 26 '22 01:09

Berendschot