Kotlin – Check if File exists

Kotlin – Check if File exists : In Kotlin, to check if the file already exists, use File.exists(). File.exists() returns a Boolean value. It returns true if the file exists and false if the file does not exist.

Example 1 – Check if File exists

In the following example we shall check if the a file “data.txt” exists.

example.kt

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 does exist.")
    } else {
        print("$fileName does not exist.")
    }
}

Output

data.txt does exist.

Conclusion

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