Kotlin – Create Directory Recursively

Kotlin – Create Directory Recursively

To create directories recursively in Kotlin, use the mkdirs() method of the File class from the java.io package.

mkdirs() method is capable of creating both the specified directory and all necessary parent directories that do not exist yet.

In this tutorial, we will demonstrate how to create directories recursively in Kotlin, with an example.

Steps to Create Directories Recursively in Kotlin

Follow these steps to create directories recursively in Kotlin:

  1. Import the File class from the java.io package.
  2. Specify the path of the directory, including any parent directories that need to be created.
  3. Create a File object with this directory path.
  4. Use the mkdirs() method on the File object to create the directory along with all necessary parent directories. This method returns true if the directory was successfully created, and false if it already exists or cannot be created.
  5. Implement error handling to manage any exceptions that may arise during the process.

Kotlin Example Program to Create Directories Recursively

The following is an example demonstrating how to create a directory structure recursively. For instance, creating a directory path like 'dir1/dir2/dir3' where ‘dir1’ and ‘dir2’ may not exist beforehand.

Main.kt

import java.io.File

fun main() {
    val directoryPath = "dir1/dir2/dir3" // Replace with your desired directory path

    val directory = File(directoryPath)
    val result = directory.mkdirs()

    if (result) {
        println("Directories created successfully: ${directory.absolutePath}")
    } else {
        println("Failed to create directories or they already exist.")
    }
}

Output

Directories created successfully: /Users/kotlinandroid/IdeaProjects/KotlinApp/dir1/dir2/dir3

The output will confirm the successful creation of the directory structure or notify if the directories already exist or cannot be created.

Summary

This Kotlin File Operations tutorial detailed the process of creating directories recursively using the mkdirs() method from the java.io.File class. The tutorial included step-by-step instructions and an example to illustrate the concept effectively.