How to read the total number of rows in a CSV file using Java?

To obtain the total number of rows in a CSV file, you can use the BufferedReader and FileReader classes in Java. Below is an example code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadCSVRowCount {
    public static void main(String[] args) {
        String csvFile = "path/to/your/csv/file.csv";
        int rowCount = 0;

        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
            String line;
            while ((line = br.readLine()) != null) {
                rowCount++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        System.out.println("Total row count: " + rowCount);
    }
}

Please replace the value of the csvFile variable with the path of the CSV file you want to read.

In the above code, we use the BufferedReader class to read the CSV file line by line. Each time a line is read, we increment the row count by 1. Finally, by printing the value of the rowCount variable, we can obtain the total number of rows in the CSV file.

广告
Closing in 10 seconds
bannerAds