Kotlin – Create Directory

Kotlin – Create Directory

Creating a directory in Kotlin can be accomplished using the mkdir() or mkdirs() methods of the File class from the java.io package.

The mkdir() method creates a single directory, while mkdirs() creates both the directory and any necessary parent directories.

This tutorial will guide you through the process of creating a directory in Kotlin, with an example.

Steps to Create a Directory in Kotlin

To create a directory in Kotlin, follow these steps:

  1. Import the File class from the java.io package.
  2. Determine the path where you want to create the directory.
  3. Create a File object with the directory path.
  4. Use the mkdir() or mkdirs() method to create the directory. mkdir() returns true if the directory was successfully created; false if it already exists or cannot be created.
  5. Handle any exceptions that might occur during the directory creation process.

Kotlin Example Program to Create a Directory

In this example, we will create a new directory named 'newdir' in the specified path.


import java.io.File

fun main() {
    val directoryPath = "newdir" // Replace with your directory path

    val directory = File(directoryPath)
    val result = directory.mkdir() // Use mkdirs() if you need to create parent directories

    if (result) {
        println("Directory created successfully: ${directory.absolutePath}")
    } else {
        println("Failed to create directory or it already exists.")


Directory created successfully: /Users/kotlinAndroid/IdeaProjects/KotlinApp/newdir

The output will indicate whether the directory was successfully created or if it failed.


In this Kotlin File Operations tutorial, we covered how to create a directory using the mkdir() and mkdirs() methods of the File class from the java.io package. The tutorial provided a step-by-step process and included a practical example for better understanding.