Traverse a directory to list files in Kotlin
This post will discuss how to traverse a directory to “recursively” list all files in Kotlin.
There are several ways to traverse a directory and list out all files present in it (and its subdirectories):
1. Using Files.walk()
function
The Files.walk()
function takes the root directory and returns a Stream<Path>
by walking the file tree recursively in a depth-first manner. After getting the Stream, you can apply a filter on it to list only regular files.
1 2 3 4 5 6 7 8 9 10 |
import java.nio.file.Files import java.nio.file.Paths fun main() { val dir = "/var/www/html" Files.walk(Paths.get(dir)) .filter { Files.isRegularFile(it) } .forEach { println(it) } } |
The above code fails to close the stream’s open directories after the stream’s operations have been completed. This function must be used within a use
control structure to ensure that all resources are closed promptly. Here’s how the code would look like:
1 2 3 4 5 6 7 8 9 10 11 |
import java.nio.file.Files import java.nio.file.Paths fun main() { val dir = "/var/www/html" Files.walk(Paths.get(dir)).use { paths -> paths.filter { Files.isRegularFile(it) } .forEach { println(it) } } } |
Here’s an equivalent solution using the Files.find()
function, which walks the file tree similar to the Files.walk()
function.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.nio.file.Files import java.nio.file.Paths import java.nio.file.attribute.BasicFileAttributes import java.util.function.BiPredicate fun main() { val dir = "/var/www/html" Files.find( Paths.get(dir), Int.MAX_VALUE, BiPredicate { _, file: BasicFileAttributes -> file.isRegularFile } ).use { paths -> paths.forEach { println(it) } } } |
2. Using Files.walkFileTree()
function
Alternatively, you can use the Files.walkFileTree()
function to walk a file tree. It requires the root directory and an instance of the file visitor to invoke for each file.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes fun main() { val dir = "/var/www/html" Files.walkFileTree(Paths.get(dir), object : SimpleFileVisitor<Path>() { override fun visitFile(path: Path, attributes: BasicFileAttributes): FileVisitResult { println(path) return FileVisitResult.CONTINUE } }) } |
That’s all about traversing a directory to recursively list all files 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 :)