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

1. Using DirectoryStream

A simple solution is to use DirectoryStream to iterate over the files in a directory that satisfies a predicate. To list all subdirectories, you can apply the filter using the File#isDirectory() function:

Download Code

2. Using Files.walk() function

To limit the number of directory levels to visit, use the Files.walk() function. Its usage is demonstrated below, which limits the directory levels to 1. A value of Int.MAX_VALUE can be used to visit all levels.

Download Code

3. Using File class

The File class provides the File#list() function to list all files and directories in a directory. The idea is to override the accept() function of the FilenameFilter interface to return true if the specified file is a directory and false otherwise.

Download Code

 
You can easily modify the code using the File#listFiles() and override the accept() function of the FileFilter interface to filter directories.

Download Code

That’s all about listing all subdirectories in a directory in Kotlin.