This post will discuss how to check if a file exists in Kotlin. The solution should return true if the file exists, and false if the file doesn’t exist or the file’s status is unknown.

1. Using File class

You can use the File.exists() function to determine if the specified file exists or not. It returns true if the file exists; false otherwise. Since a file can be a directory, the function returns true when the specified path points to a directory. To handle this, additionally check for a directory using the File.isDirectory() function. This is demonstrated below:

Download Code

 
You can avoid an additional check for a directory using the File.isFile() function. It tests whether the specified path points to a regular file, and not a directory.

Download Code

2. Using Files class

To check for a file’s existence, you can use Files.exists() and Files.notExists() function along with the Files.isDirectory() function. The exists() function returns true if the file exists (or if the specified path points to a directory), whereas the notExists() function returns true when it does not exist.

Note that if both exists() and notExists() return false, the existence of the file cannot be verified. This can happen when the program does not have access to the file.

Download Code

 
Alternatively to check if a path is a regular file (and not a directory), use the Files.isRegularFile() function:

Download Code

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