Kotlin – Read File to String

Kotlin – Read File to String

To read a text file to a string in Kotlin, you can use readText() method of java.io.File class.

In this tutorial, we shall see a step by step guide on how to read a text file to a string variable in Kotlin, and an example program to read 'example.txt' to a string variable.

Steps to read content of a text file to a string

The following is a step by step process to read a text file to a string, where the text file is given by a filePath.

  1. Import java.io.File class.
  2. Consider that the file path is given in filePath variable.
  3. Inside the try block, use File(filePath).readText() to directly read the contents of the file into the fileContent variable.
  4. Check for any exceptions in the catch block and handle them as needed.

Example Program to read ‘example.txt’ to a string

In this example, we have a text file example.txt which we read the contents to a string variable.

Main.kt

import java.io.File

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

    try {
        val fileContent = File(filePath).readText()

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

Output

File content
-------------
This is sample content.
This is a line.
This is another line.

Summary

Summarizing this Kotlin File Operations tutorial, we have seen how to read a text file to a string using java.io.File.readText() method, with a well detailed step by step process, and an example program.