How to get the total number of rows in CSV or text Files?
- In Java, we can get Total numbers of rows in CSV files or Text files using File and BufferedReader class which are available in java.io package.
- Let's say, we have CSV and text files in a directory having a specific number of rows in each file like below:
Get rows from files |
Read the number of rows in files |
Observer here, csvFile1 has 5 rows,csvFile2 has 4 rows and File1.txt has 3 rows.
Demo on Reading number of rows in Files:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class csvCountDemo {
public static void main(String args[]) throws Exception {
String filePath;
String directorypath = "D:\\Sessions\\csvFiles";
List<Integer> rowsCount = new ArrayList<>();
File directory = new File(directorypath);
String[] fileList = directory.list();
for (String name : fileList) {
System.out.println("file Name=" + name);
filePath = directorypath + "\\" + name;
System.out.println("File path=" + filePath);
BufferedReader br = new BufferedReader(new FileReader(filePath));
String input;
int count = 0;
while ((input = br.readLine()) != null) {
count++;
}
System.out.println("Total number of rows in " + name + " file=" + count);
rowsCount.add(count);
System.out.println("added " + count + " to the list");
System.out.println("-------------------------------");
}
int sum;
sum = rowsCount.stream().mapToInt(Integer::intValue).sum();
System.out.println("Total number of rows in all csv files=" + sum);
}
}
Output:
file Name=csvFile1.csv
File path=D:\path\csvFiles\csvFile1.csv
Total number of rows in csvFile1.csv file=5
added 5 to the list
-------------------------------
file Name=csvFile2.csv
File path=D:\path\csvFiles\csvFile2.csv
Total number of rows in csvFile2.csv file=4
added 4 to the list
-------------------------------
file Name=File1.txt
File path=D:\path\csvFiles\File1.txt
Total number of rows in File1.txt file=3
added 3 to the list
-------------------------------
Total number of rows in all csv files=12
No comments:
Post a Comment
Please comment below to feedback or ask questions.