Kotlin – Check if File exists

To check if a file already exists, in Kotlin, use exists() function of the java.io.File class. File.exists() returns a Boolean value of true if the file exists, or false if the file does not exist.

Example

In the following example we shall check if the file "data.txt" exists.

Main.kt

</>
Copy
import java.io.File

fun main(args: Array<String>) {
    val fileName = "data.txt"
    var file = File(fileName)
    var fileExists = file.exists()

    if(fileExists){
        print("$fileName exists.")
    } else {
        print("$fileName does not exist.")
    }
}

Output

data.txt exists.

Conclusion

In this Kotlin Tutorial, we learned how to check if a File exists using File.exists() method.