In this section, you will learn how to count only files in a directory.
In this section, you will learn how to count only files in a directory.In this section, you will learn how to count only files in a directory.
You have learnt various file operations. Here we are going to find out the number of files from a directory. You can see in the given example, we have created an instance of File class and specify a directory in the constructor of File class. Then we have called listFile() method through the File object to return an array of files and directory available in the given directory. But we have to count the number of files so we have initialized a counter whose value will get incremented if it finds the file in a specified directory. Finally this counter value determine the number of files.
isFile(): This method of File class determines whether the pathname of the object represented by a File object is a file.
listFiles(): This method of File class returns an array of pathnames denoting the files in the directory.
Here is the code:
import java.io.*; public class CountFilesInDirectory { public static void main(String[] args) { File f = new File("C:/Text"); int count = 0; for (File file : f.listFiles()) { if (file.isFile()) { count++; } } System.out.println("Number of files: " + count); } }
Through the above code, you can count the number of files available in the directory.
Output:
Number of files: 4 |