Table of Contents
Using java.io.File
Class
Before moving forwards, it is important to know the available items in the current directory. You may also create the same structure to follow along with this article. Our current directory (E:\Test) has the following structure:
- E:\Test – It has seven items, four text files and three folders (
FolderA
,FolderB
,FolderC
,File1.txt
,File2.txt
,File3.txt
, andFile4.txt
). - E:\Test\FolderA – It contains four text files (
File1.txt
,File2.txt
,File3.txt
, andFile4.txt
). - E:\Test\FolderB – It has two text files (
File1.txt
andFile2.txt
). - E:\Test\FolderC – Only one text file lives here (
File1.txt
).
Use File.listFiles()
Method
We can use File.listFiles()
method in the following four scenarios:
- To count files in the current directory, excluding sub-directories.
- To count files in the current directory, including sub-directories.
- To count files and folders in the current directory, excluding sub-directories.
- To count files and folders in the current directory, including sub-directories.
Note that the code will be similar to one another for all the above situations except for small changes. So, we will thoroughly learn the first code example and later only discuss the part different from the previous one. So, let’s start with the first example code below.
Count Files in the Current Directory (Excluding Sub-directories)
To count files in the current directory, excluding sub-directories:
- Instantiate the
File
class by specifying the directory. - Call a function we defined to count the files only in the current parent directory.
- Inside the function, we invoked in the previous step, use a
for
loop to iterate over all items in the specified directory. - Use the
if
statement to check whether it is a file. If it is, increment the counter by1
; otherwise, move to the next iteration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.io.File; import java.io.IOException; public class CountFilesInDirectory { public static void main(String[] args) throws IOException { File directory = new File("E:\\Test"); int fileCount = countFilesInCurrentDirectory(directory); System.out.println("Number of Files:" + fileCount); } public static int countFilesInCurrentDirectory(File directory) { int count = 0; for (File file: directory.listFiles()) { if (file.isFile()) { count++; } } return count; } } |
1 2 3 |
Number of Files:4 |
In the main
method of the CountFilesInDirectory
class, we created an object of the File
class (instantiated the File
class) by specifying an E:\Test directory and saved its reference in directory
variable.
Next, we called the countFilesInCurrentDirectory()
method and passed the File
object named directory
we created in the previous step. On successful execution of this method, it returned a file counter that we saved in the fileCount
variable. So, let’s see how this method counts the files.
The countFilesInCurrentDirectory()
is a static
method defined in the CountFilesInDirectory
class to count files in the provided directory
. We declared and initialized a count
variable used to maintain a file counter inside this function.
Next, we used a for
loop with the listFiles()
method to iterate over every item in the specified directory. We used the if
statement with the isFile()
function for each iteration to check whether the current item is a file. We incremented the count
variable by 1
if the if
condition is fulfilled; otherwise, we moved to the next iteration.
Once the loop was over, we returned the count
variable, whose value will be saved in the fileCount
variable, which will be used to print a message on the console using the System.out.println()
method.
Now, the point is what the listFiles()
and isFile()
methods are doing here. The listFiles() is one of the methods of the File
class, which returns an array of abstract pathnames representing the directories and files in the specified directory denoted by this abstract pathname which satisfies the given filter (if any).
Remember, we will only get an array of files if the given path is a directory; otherwise, it will generate a java.lang.NullPointerException
exception and return null
.
The listFiles()
method is an overloaded method, which means we can use it in the following three ways where the first method does not take any parameter, the second accepts the FilenameFilter
object, and the third takes FileFilter
object as their parameters (we used the first method in our code above).
1 2 3 4 5 |
public File[] listFiles() public File[] listFiles(FilenameFilter filter) public File[] listFiles(FileFilter filter) |
Moving to the next method, which is isFile()
. It is also a method of the File
class, used to check whether the file represented by an abstract pathname is the normal file. This function returns a Boolean value, True
if the current item is a file; otherwise, False
.
Count Files in the Current Directory (Including Sub-directories)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.io.File; import java.io.IOException; public class CountFilesInDirectory { public static void main(String[] args) throws IOException { File directory = new File("E:\\Test"); int fileCount = countFilesInDirectory(directory); System.out.println("Number of Files:" + fileCount); } public static int countFilesInDirectory(File directory) { int count = 0; for (File file: directory.listFiles()) { if (file.isFile()) { count++; } if (file.isDirectory()) { count += countFilesInDirectory(file); } } return count; } } |
1 2 3 |
Number of Files:11 |
This code example is the same, but we added another if
statement inside the for
loop in the countFilesInDirectory()
method (line 19 to line 21). This if
statement used the isDirectory()
method to check whether the current item is a directory.
Like the isFile()
method, it also returned a Boolean value, True
if the condition is satisfied; otherwise, False
. If the condition is fulfilled, the countFilesInDirectory()
method calls a copy of itself, getting the current item (a directory) as a parameter.
NOTE: We used recursion here because countFilesInDirectory()
method is calling a copy of itself.
Count Files & Folders in Current Directory (Excluding Sub-directories)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.File; import java.io.IOException; public class CountFilesInDirectory { public static void main(String[] args) throws IOException { File directory = new File("E:\\Test"); int fileCount = countFilesInDirectory(directory); System.out.println("Number of Files:" + fileCount); } public static int countFilesInDirectory(File directory) { int count = 0; for (File file: directory.listFiles()) { count++; } return count; } } |
1 2 3 |
Number of Files:7 |
Inside the for
loop in the countFilesInDirectory()
method, we removed both if
statements to count files and folders from the current parent directory. Note that we are still incrementing the count
variable by 1
in each iteration. For example, we got 7
because E:\Test contains four text files and three folders (FolderA
, FolderB
, FolderC
, File1.txt
, File2.txt
, File3.txt
, and File4.txt
).
Count Files & Folders in Current Directory (Including Sub-directories)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.io.File; import java.io.IOException; public class CountFilesInDirectory { public static void main(String[] args) throws IOException { File directory = new File("E:\\Test"); int fileCount = countFilesInDirectory(directory); System.out.println("Number of Files:" + fileCount); } public static int countFilesInDirectory(File directory) { int count = 0; for (File file: directory.listFiles()) { count++ if (file.isDirectory()) { count += countFilesInDirectory(file); } } return count; } } |
1 2 3 |
Number of Files:14 |
This code is similar to the immediate previous example. But, we have an if
statement in the for
loop (line 16 to line 18), which assesses if the current item is a directory or not using the isDirectory()
method.
If it is, we also used recursion to count files in that directory. You can compare the above output by looking at the directory structure given at the beginning of this article.
If you are not concerned about sub-directories and only want to count files and folders in the current parent directory, then we can use the most straightforward solution using the File.list()
method.
Use File.list()
Method
To count files and folders in the current parent directory, excluding sub-directories:
- Create an object of the
File
class by passing a directory as an argument. - Use the
.list()
method to get a String-type array containing filenames (files and folders). - Use the
.length
property of the String type array (received from the previous step) to get a count of the array elements.
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.io.File; public class CountFilesInDirectory { public static void main(String[] args) { File directory = new File("E:\\Test"); String[] fileArray = directory.list(); int fileCount = fileArray.length; System.out.println("Number of Files:" + fileCount); } } |
1 2 3 |
Number of Files:7 |
The above code fence is similar to the previous code examples except for one difference; we used the .list()
method here. After instantiating the File
class, we used the .list()
method to get an array of strings with filenames (files and directories) in the directory represented by this abstract pathname.
We saved this array in the fileArray
variable; after that, we accessed the .length
property of the fileArray
array to know the count of elements in it, which we used to print a message on the console using println()
method.
We can also replace line 7 with File[] fileArray = directory.listFiles();
and get the same results. Now, the question is, how does the File.list()
method differ from File.listFiles()
? Both methods essentially do the same but:
File.list()
method returns aString array
containing filenames (directories and files).File.listFiles()
returns anarray of the File class
of the same.
Now, where to choose which method? We must choose between these two methods wherever we are concerned about speed and memory consumption. Usually, a String array (returned by File.list()
) would be faster and consume less memory as compared to the File array (returned by File.listFiles()
). To dive into more details, you can check this page.
Further reading:
Using java.nio.file.DirectoryStream
Class
The StreamAPI
approach is useful when we:
- Do not want to use the
Java.io.File
class. - Look for a solution using fewer resources while working with large directories.
- More responsive while working with remote directories.
In this article, we are using the DirectorySteam
class to do the following:
- To count files in the current directory, excluding sub-directories.
- To count files in the current directory, including sub-directories.
- To count files and folders in the current directory, excluding sub-directories.
- To count files and folders in the current directory, including sub-directories.
Again, the code sample will be similar to one another for all the above scenarios so that we will learn each step for the first example code, later, will explain the newly added piece of code only.
Count Files in the Current Directory (Excluding Sub-directories)
To count files in the current directory, excluding sub-directories:
- Create an ArrayList of Strings.
- Create a directory stream to access the contents of the given directory.
- Use the
for
loop to iterate over the directory steam created in the previous step. - For every iteration of the
for
loop, use theif
to check if the current item is not a directory. If not, use the.add
method to add the current string item to ArrayList. - Use the
.size()
method to get the size of the ArrayList. - Use the
try-catch
method to handle exceptions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class CountFilesInDirectory { public static void main(String[] args) { List<String> fileNames = new ArrayList<>(); try { DirectoryStream<Path> directoryStream = Files .newDirectoryStream(Paths.get("E:\\Test")); for (Path path: directoryStream) { if(!Files.isDirectory(path)) fileNames.add(path.toString()); } } catch (IOException exception){ exception.printStackTrace(); } System.out.println("Number of Files:" + fileNames.size()); } } |
1 2 3 |
Number of Files:4 |
Inside the main
method of the CountFilesInDirectory
class, we created a new ArrayList
of Strings called fileNames
. The ArrayList is a class in Java that implements the List
interface and provides an array-like data structure for storing elements. The diamond operator
will hold. In this case, it is a list of Strings. is a shorthand notation specifying the type of elements the
ArrayList
Inside the try
block, we created a new DirectoryStream called directoryStream
that was used to access the directory’s contents. Note that the DirectoryStream
is of type Path
. The Files.newDirectoryStream
method created a new directory stream bound to the specified directory. Here, the Paths.get("E:\\Test")
was used to obtain a Path
object representing the file system directory E:\Test.
Next, we used a for
loop to iterate over each element in the directoryStream
object and assigned it to the variable path
of type Path
. For each iteration, we checked if the path
is not a directory by calling the Files.isDirectory(path)
method in the if
statement; if it is not a directory, it will add the path
to the fileNames
list. Finally, the path.toString()
method was used to get the string representation of the path
.
The for
loop was used to iterate over the contents of the directory and only added the file names to the fileNames
list, not the directory names.
Here, if the try
block generates the IOException
(a type of exception thrown when an input/output operation fails), the catch
block will be executed. The exception.printStackTrace()
method was called inside the catch
block, which printed the stack trace of the exception
to the console. The stack trace shows the sequence of method calls that led to the exception
, which can be helpful for debugging.
Finally, we used the .size()
method to get the size of the fileNames
list and print it on the console.
Count Files in the Current Directory (Including Sub-directories)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class CountFilesInDirectory { public static void main(String[] args) { List<String> fileNames = new ArrayList<>(); try { DirectoryStream<Path> directoryStream = Files .newDirectoryStream(Paths.get("E:\\Test")); for (Path path: directoryStream) { if(Files.isDirectory(path)){ DirectoryStream<Path> subDirectoryStream = Files .newDirectoryStream(Paths.get(path.toString())); for (Path p: subDirectoryStream) fileNames.add(p.toString()); } else{ fileNames.add(path.toString()); } } } catch (IOException exception){ exception.printStackTrace(); } System.out.println("Number of Files:" + fileNames.size()); } } |
1 2 3 |
Number of Files:11 |
This code is similar to the immediate previous example, but we replaced the following
1 2 3 4 |
if(!Files.isDirectory(path)) fileNames.add(path.toString()); |
with
1 2 3 4 5 6 7 8 9 10 11 |
if(Files.isDirectory(path)){ DirectoryStream<Path> subDirectoryStream = Files .newDirectoryStream(Paths.get(path.toString())); for (Path p: subDirectoryStream) fileNames.add(p.toString()); } else{ fileNames.add(path.toString()); } |
inside the for
loop. We did so to check if the current path
is a directory or not using the Files.isDirectory(path)
method. If it is a directory, we created a new subDirectoryStream
using Files.newDirectoryStream(Paths.get(path.toString()))
, which was used to access the contents/items of the sub-directory represented by the current path
.
Next, we iterated over each element in the subDirectoryStream
object and assigned it to the variable p
of type Path
and added the path to the fileNames
list using the .add()
method. On the other hand, in the else
part, we directly added the path
to fileNames
.
Note that this code was used to recursively iterate over the contents of the directory/subdirectories and add the file names to the fileNames
list, not the directory names.
Count Files & Folders in the Current Directory (Excluding Sub-directories)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class CountFilesInDirectory { public static void main(String[] args) { List<String> fileNames = new ArrayList<>(); try { DirectoryStream<Path> directoryStream = Files .newDirectoryStream(Paths.get("E:\\Test")); for (Path path: directoryStream) { fileNames.add(path.toString()); } } catch (IOException exception){ exception.printStackTrace(); } System.out.println("Number of Files:" + fileNames.size()); } } |
1 2 3 |
Number of Files:7 |
For this code, we removed all the conditionals from the for
loop located in the main
method to count files and folders from the current parent directory.
Count Files & Folders in the Current Directory (Including Sub-directories)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class CountFilesInDirectory { public static void main(String[] args) { List<String> fileNames = new ArrayList<>(); try { DirectoryStream<Path> directoryStream = Files .newDirectoryStream(Paths.get("E:\\Test")); for (Path path: directoryStream) { fileNames.add(path.toString()); if(Files.isDirectory(path)){ DirectoryStream<Path> subDirectoryStream = Files .newDirectoryStream(Paths.get(path.toString())); for (Path p: subDirectoryStream) fileNames.add(p.toString()); } } } catch (IOException exception){ exception.printStackTrace(); } System.out.println("Number of Files:" + fileNames.size()); } } |
1 2 3 |
Number of Files:14 |
This code is similar to the code where we were counting files in the current directory, including sub-directories; here, we eliminated the else
block to count files and folders from the current directory/sub-directories.’
That’s all about how to count files in Directory in Java.