0
0
KotlinHow-ToBeginner · 3 min read

How to Check if a File Exists in Kotlin Easily

In Kotlin, you can check if a file exists by creating a File object with the file path and calling its exists() method. This method returns true if the file is present and false if it is not.
📐

Syntax

Use the File class from java.io package. Create a File object with the file path as a string. Then call exists() on that object to check if the file is there.

  • File(path: String): Creates a file object for the given path.
  • exists(): Boolean: Returns true if the file exists, otherwise false.
kotlin
import java.io.File

val file = File("path/to/your/file.txt")
val doesExist = file.exists()
💻

Example

This example shows how to check if a file named example.txt exists in the current directory and prints a message accordingly.

kotlin
import java.io.File

fun main() {
    val file = File("example.txt")
    if (file.exists()) {
        println("File exists.")
    } else {
        println("File does not exist.")
    }
}
Output
File does not exist.
⚠️

Common Pitfalls

One common mistake is to check the file path incorrectly or forget that exists() checks the exact path given. Also, exists() returns true if the path is a directory or a file, so be sure you want to check for a file or directory.

Another pitfall is not importing java.io.File, which causes errors.

kotlin
import java.io.File

fun main() {
    val file = File("wrong/path/to/file.txt")
    // This will print "false" even if a file exists elsewhere
    println(file.exists())

    val dir = File(".")
    println(dir.exists()) // true, but this is a directory, not a file
}
Output
false true
📊

Quick Reference

Remember these quick tips when checking file existence in Kotlin:

  • Use File(path).exists() to check presence.
  • Ensure the path is correct and accessible.
  • exists() returns true for files and directories.
  • Use isFile or isDirectory to distinguish file types.

Key Takeaways

Use the File class and its exists() method to check if a file exists in Kotlin.
Make sure the file path is correct and accessible to get accurate results.
exists() returns true for both files and directories; use isFile or isDirectory to differentiate.
Always import java.io.File to avoid compilation errors.
Checking file existence is a simple boolean check that helps avoid errors when accessing files.