Kotlin – Check if a Directory Exists

Check if a Directory Exists using Kotlin

To check if a directory exists in Kotlin, you can use the File class from the java.io package. This method involves verifying the existence of a directory at a specified path.

In this tutorial, we’ll learn how to check if a directory exists in Kotlin, with an example.

Steps to Check if a Directory Exists in Kotlin

To determine if a directory exists in Kotlin, you can follow these steps:

  1. Import the File class from the java.io package.
  2. Create a File object using the path of the directory you want to check.
  3. Use the exists() method to check if the file or directory exists.
  4. Additionally, use the isDirectory() method to confirm that the path is a directory and not a file.

Kotlin Example Program to Check if a Directory Exists

Below is an example that demonstrates how to check if a directory named 'exampleDir' exists.

Main.kt

import java.io.File

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

    val directory = File(directoryPath)
    if (directory.exists() && directory.isDirectory) {
        println("Directory exists.")
    } else {
        println("Directory does not exist.")
    }
}

Output

Directory exists.

Now, let us take a directory that does not exist, say 'dummyDir' exists.

Main.kt

import java.io.File

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

    val directory = File(directoryPath)
    if (directory.exists() && directory.isDirectory) {
        println("Directory exists.")
    } else {
        println("Directory does not exist.")
    }
}

Output

Directory does not exist.

Summary

In this tutorial, we demonstrated how to check if a directory exists at a specified path. This method is crucial for validating the existence of directories before performing file operations.