Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

csvParser.getRecords() returns empty when there are records in CSVParser

I'm using following dependency for reading the csv file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.5</version>
</dependency>

Below is the code that I've written to read the csv file:

Reader reader = Files.newBufferedReader(Paths.get(file.getPath()));
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
for(CSVRecord csvRecord: csvParser) {
     System.out.println(csvRecord.get(0));
}

I can read every line from the csv file by the above method. But csvParser.getRecords(); returns empty. I want the total number of lines in the CSV file. How can I do this?

like image 261
User1230321 Avatar asked Dec 22 '25 03:12

User1230321


1 Answers

Read the getRecords() javadoc carefully (emphasis is mine):

The returned content starts at the current parse-position in the stream.

You said :

But csvParser.getRecords(); returns empty. I want the total number of lines in the CSV file. How can I do this?

You have to invoke csvParser.getRecords().size(); before iterating records. Then iterate them.

For example :

List<Records> records = csvParser.getRecords();
int nbRecords = records.size();
for(CSVRecord csvRecord: records) {
     System.out.println(csvRecord.get(0));
}
like image 165
davidxxx Avatar answered Dec 23 '25 17:12

davidxxx