List all subdirectories of a directory in Kotlin
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.IOException import java.nio.file.FileSystems import java.nio.file.Files fun main() { val path = "/path/to/dir" try { Files.newDirectoryStream(FileSystems.getDefault().getPath(path)) { Files.isDirectory(it) } .use { ds -> ds.forEach { println(it.fileName) } } } catch (e: IOException) { e.printStackTrace() } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.nio.file.Files import java.nio.file.Paths import kotlin.streams.toList fun main() { val path = "/path/to/dir" val dirs = Files.walk(Paths.get(path), 1) .filter { Files.isDirectory(it) }.toList() println(dirs) } |
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.
|
1 2 3 4 5 6 7 |
import java.io.File fun main() { val path = "/path/to/dir" val directories = File(path).list { dir, name -> File(dir, name).isDirectory} println(directories?.contentToString()) } |
You can easily modify the code using the File#listFiles() and override the accept() function of the FileFilter interface to filter directories.
|
1 2 3 4 5 6 7 |
import java.io.File fun main() { val path = "/path/to/dir" val directories = File(path).listFiles { pathname -> pathname.isDirectory } println(directories!!.contentToString()) } |
That’s all about listing all subdirectories in a directory in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)