Check if a directory exists in Kotlin
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.io.File fun main() { val directoryPath = "/var/kotlin/" val file = File(directoryPath) if (file.isDirectory) { println("File is a Directory") } else { println("Directory doesn't exist!!") } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.nio.file.Files import java.nio.file.Paths fun main() { val directoryPath = "/var/kotlin/" val path = Paths.get(directoryPath) val isDir = Files.isDirectory(path) if (isDir) { println("File is a Directory") } else { println("Directory doesn't exist!!") } } |
That’s all about checking if a directory exists in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)