Kotlin – Read File

Kotlin – Read File

To reading a file in Kotlin, you can use the readText() method of the File class from the java.io package. This method reads the entire content of a file into a single String, making it convenient for smaller files.

In this tutorial, we’ll explore how to read the contents of a file in Kotlin with an example.

Steps to Read a File in Kotlin

Follow these steps to read a file in Kotlin:

  1. Import the File class from the java.io package.
  2. Specify the path of the file to be read.
  3. Create a File object using the specified file path.
  4. Use the readText() method to read the content of the file. Ensure that the file size is not too large for this method.
  5. Handle exceptions using a try-catch block to catch any IOException that might occur during file reading.

Kotlin Example Program to Read a File

In this example, we’ll read the contents of a file named 'example.txt'.

Main.kt

import java.io.File

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

    try {
        val file = File(filePath)
        val content = file.readText()

        println("File Content: \n$content")
    } catch (e: Exception) {
        println("An error occurred while reading the file: ${e.message}")
    }
}

Output

File Content: 
apple is red.
apple is almost round in shape.
There are more apples than pineapples.

The output will display the contents of the file read by the program.

Summary

In this Kotlin File Operations tutorial, we demonstrated how to read the contents of a file using the readText() method of the File class from the java.io package, complete with a practical example.