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?
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));
}
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