Kotlin – Check if File is Empty

Kotlin – Check if File is Empty

To check if a file is empty in Kotlin, you can use the length() method provided by the java.io.File class. If the length of the file is zero, it means the file is empty.

In this tutorial, we shall see a detailed step by step process to check if file at give file path is empty or not, with examples.

Steps to Check if File is Empty

Follow these steps to check if file at given file path is empty or not.

  1. Import java.io.File class.
  2. Given file path in filePath variable. We need to check if this file is empty or not.
  3. Create a File object using the file path filePath.
  4. Check if the file exists using the exists() method.
  5. If the file exists, use the length() method to get the size of the file and compare it to zero to determine if the file is empty.
  6. Print the appropriate message based on whether the file is empty or not.

Example Program to check if File is Empty

In this example program, we shall check if the file 'example.txt' is empty or not.

If you observe in the following screenshot, the size of the given file is zero bytes.

Kotlin - Check if File is Empty - First example

Main.kt

import java.io.File

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

    val file = File(filePath)

    if (file.exists()) {
        if (file.length() == 0L) {
            println("The file '$filePath' is empty.")
        } else {
            println("The file '$filePath' is not empty.")
        }
    } else {
        println("The file '$filePath' does not exist.")
    }
}

Output

The file 'example.txt' is empty.

Now, let us take a file 'example_1.txt' which is of size 11 bytes, i.e., not empty.

Kotlin - Check if File is Empty - Second example

Change the file path and run the program.

Main.kt

import java.io.File

fun main() {
    val filePath = "example_1.txt"

    val file = File(filePath)

    if (file.exists()) {
        if (file.length() == 0L) {
            println("The file '$filePath' is empty.")
        } else {
            println("The file '$filePath' is not empty.")
        }
    } else {
        println("The file '$filePath' does not exist.")
    }
}

Output

The file 'example_1.txt' is not empty.

Summary

In this Kotlin File Operations tutorial, we have seen how to check if given file is empty or not, using java.io.File.length() method.