Kotlin – Check if a File is Readable

Kotlin – Check if a File is Readable

Checking if a file is readable in Kotlin is a simple yet important task, especially when your application needs to process or read files. Kotlin makes it easy to check a file’s readability using the File class from the java.io package.

To check if a file is readable in Kotlin, you can use File.canRead() function.

In this tutorial, we will go through step by step process of how to check if a file is readable in Kotlin, with an example.

Steps to Check if a File is Readable in Kotlin

To check if a file is readable in Kotlin, follow these steps:

  1. Import the File class from the java.io package.
  2. Create a File object with the path of the file you want to check.
  3. Use the canRead() method of the File object to check if the file is readable.

Kotlin Example Program to Check if a File is Readable

In the following example program, we will check if a file named 'example.txt' is readable.

Main.kt

import java.io.File

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

    if (file.canRead()) {
        println("The file is readable.")
    } else {
        println("The file is not readable.")
    }
}

Output

The file is readable.

The output will indicate whether the specified file is readable or not.

Summary

In this Kotlin tutorial, we learned how to check if a file is readable. This is a crucial check in many file-handling operations, ensuring that your application can safely read from the specified file without encountering access errors.