Kotlin – Iterate Over Directory Recursively

Iterate Over Directory Recursively in Kotlin

Iterating over a directory recursively in Kotlin allows you to process not just the files in a given directory, but also the files in all of its subdirectories. This is particularly useful for applications that need to work with complex directory structures.

To iterate over a directory recursively in Kotlin, task using the File class and its walk() method from the java.io package.

In this tutorial, we will learn to iterate over a directory and its subdirectories recursively in Kotlin, with an example program.

Steps to Iterate Over a Directory Recursively in Kotlin

To recursively iterate over a directory in Kotlin, follow these steps:

  1. Import the File class from the java.io package.
  2. Create a File object pointing to the root directory you want to iterate over.
  3. Use the walk() method to create a sequence of all files and directories starting from the root directory.
  4. Iterate over the sequence to process each file and directory as needed.

Kotlin Example Program to Iterate Over a Directory Recursively

In the following example program, we iterate over a directory named 'exampleDir' and its subdirectories, printing out the absolute paths of all files and directories:

Kotlin Example Program to Iterate Over a Directory Recursively

Main.kt

import java.io.File

fun main() {
    val rootDirectoryPath = "exampleDir" // Replace with your directory path
    val rootDirectory = File(rootDirectoryPath)

    rootDirectory.walk().forEach { file ->
        println(file.absolutePath)
    }
}

Output

/Users/ka/IdeaProjects/KotlinApp/exampleDir
/Users/ka/IdeaProjects/KotlinApp/exampleDir/data.json
/Users/ka/IdeaProjects/KotlinApp/exampleDir/innerDirectory
/Users/ka/IdeaProjects/KotlinApp/exampleDir/innerDirectory/example_2.txt
/Users/ka/IdeaProjects/KotlinApp/exampleDir/innerDirectory/output.txt
/Users/ka/IdeaProjects/KotlinApp/exampleDir/example.txt
/Users/ka/IdeaProjects/KotlinApp/exampleDir/output.txt

The output will list the names of all files and directories within the specified root directory and its subdirectories.

Summary

In this Kotlin tutorial, we learned how to recursively iterate over a directory and its subdirectories using File.walk(), with detailed steps and example.