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
}
}
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.
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:
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:
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:
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With