This post will discuss how to list all subdirectories present a directory in Java.

1. Using File#list() method

The File#list() method is used to get the files and directories in a directory that satisfy the specified file name filter. You can override the accept() method of the FilenameFilter that returns true if the specified file should be included in the file list; false otherwise. To list all subdirectories, return true if and only if the file is a directory.

Download Code

 
The above code can be further shortened with Java 8 lambdas, as shown below:

Download Code

2. Using File#listFiles() method

You can also use the File#listFiles() method to get a pathname list of the files and directories in the specified directory that satisfy the specified file filter. You can override the accept() method of the FileFilter that checks whether the supplied pathname should be included in the output.

Download Code

 
The above code is equivalent to the following, which uses method reference:

Download Code

3. Using DirectoryStream

Alternatively, you can use the DirectoryStream to iterate over the files in a directory that satisfy some condition. Here’s a simple example of its usage to filter only directories:

Download Code

4. Using Files.walk() method

If you need to limit the maximum number of directory levels to visit, consider using the Files.walk() method that returns a Stream<Path>. It is available since JDK 1.8. To visit all levels, you can pass Integer.MAX_VALUE value.

Download Code

That’s all about listing all subdirectories present a directory in Java.