Kotlin – Check if File Exists

Kotlin – Check if File Exists

To check if file exists in Kotlin, you can use exists() method of java.io.File class. Get the File object for given file path, and call exists() method on the File object. The exists() method returns true if the file exits, or false otherwise.

In this tutorial, we will go through a step by step guide on how to check if a file exits at given path, with an example.

Steps to check if File exists in Kotlin

Follow these steps to check if a File exists at given filePath.

  1. Import the necessary java.io.File class.
  2. Set the filePath variable to the path of the file you want to check.
  3. Create a File object using the specified file path.
  4. Use the exists() method of the File object to check if the file exists. Use the return value of exists() method as a condition in an if else statement.
  5. Print a message indicating whether the file exists or not.

Kotlin Example Program to check if File Exists

In this example, we shall check if the file "example.txt" exists using File.exists() method.

Kotlin - Check if File Exists

Main.kt

import java.io.File

fun main() {
    // Given file path
    val filePath = "example.txt" // Replace with the path to your file

    // Create File object with the file path
    val file = File(filePath)

    // Check if file exists
    if (file.exists()) {
        println("The file '$filePath' exists.")
    } else {
        println("The file '$filePath' does not exist.")
    }
}

Output

The file 'example.txt' exists.

Now, let us take a file path that does not exist, say, 'sample.txt'. No 'sample.txt is present at the root of our Kotlin project. Let us verify the same using File.exists() method.

Main.kt

import java.io.File

fun main() {
    // Given file path
    val filePath = "sample.txt"

    // Create File object with the file path
    val file = File(filePath)

    // Check if file exists
    if (file.exists()) {
        println("The file '$filePath' exists.")
    } else {
        println("The file '$filePath' does not exist.")
    }
}

Output

The file 'sample.txt' does not exist.

Summary

In this Kotlin File Operations tutorial, we have seen how to check if a file exists at given file path using File.exists() method of java.io package, with step by step guide, and an example program.