Home Tutorial Java Core Files Java count files in a directory

 
 

Share on Google+Share on Google+
Java count files in a directory
Posted on: April 27, 2006 at 12:00 AM
Advertisement
In this section, you will learn how to count only files in a directory.

Java count 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
Advertisement

Related Tags for Java count files in a directory:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 27, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com