How to Check if a File Exists in Kotlin

In Kotlin, we can use the File built-in exists() method to check if a file exists.

1. Using Kotlin to Check if a File Exists

In Kotlin, we use the exists() function from the File class. Here’s how it looks:

CheckFile.kt

import java.io.File

fun main() {
    val file = File("example.txt")

    if (file.exists()) {
        println("File exists!")
    } else {
        println("File does not exist!")
    }
}

2. Comparison with Java

In Java, checking if a file exists is also simple but slightly more verbose:

Java Example

FileExistenceCheck.java

import java.io.File;


import java.io.File;

public class FileExistenceCheck {

    public static void main(String[] args) {
        File file = new File("example.txt");

        if (file.exists()) {
            System.out.println("File `" + file.getName() + "` exists!");
        } else {
            System.out.println("File `" + file.getName() + "` does not exist!");
        }
    }

}

Kotlin Example

FileExistenceCheck.kt

import java.io.*

fun main() {
    val file = File("example.txt")

    if (file.exists()) {
        println("File `$file` exists!")
    } else {
        println("File `$file` does not exist!")
    }
}

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments