This post will discuss how to check if a directory exists in Kotlin.

When checking for a directory’s existence, three outcomes are possible:

  • The directory exists.
  • The directory doesn’t exist.
  • The directory’s status is unknown as the program does not have access to it.

Each of the following solutions returns true if the directory exists; false otherwise.

1. Using File.isDirectory() function

To check for the directory’s existence in Kotlin, you can use the File.isDirectory() function. It returns true if the directory exists; false otherwise. A typical invocation for this method would look like:

Download Code

2. Using Files.isDirectory() function

Alternately, you can use the static function Files.isDirectory() to check for a directory’s existence. It returns true when the specified path points to a directory. This function is demonstrated below:

Download Code

That’s all about checking if a directory exists in Kotlin.