In this Kotlin tutorial, you shall learn how to check if a given directory exists, using File.exists() function, with example programs.

Kotlin – Check if directory exists

To check if a specific directory exists in Kotlin, we can use exists() function from the java.io.File class.

Steps to check if a given directory is present

Consider that we are given a path to a directory.

Create a File object with the given directory path, and then call exists() on the File object. If the file exists, the function returns true, or else, it returns false.

</>
Copy
val directory = File("path/to/directory")
directory.exists()

Examples (2)

1. Check if directory exists

In the following program, we check if the directory mydata exists.

We have a directory named mydata in the project folder. Therefore the function must return true, and the if-block must execute.

Main.kt

</>
Copy
import java.io.File

fun main() {
    val directory = File("mydata")
    if (directory.exists()) {
        println("Directory exists.")
    } else {
        println("Directory does not exist.")
    }
}

Output

Directory exists.

Reference tutorials for the above program

2. Directory does not exist

In this example, we shall take a name of the directory that does not exist, say temp, and programmatically check using File.exists() function.

Main.kt

</>
Copy
import java.io.File

fun main() {
    val directory = File("temp")
    if (directory.exists()) {
        println("Directory exists.")
    } else {
        println("Directory does not exist.")
    }
}

Output

Directory does not exist.

Reference tutorials for the above program

Conclusion

In this Kotlin Tutorial, we learned how to create a new directory using File.mkdir() function.