Kotlin – Read Text File Line by Line

Kotlin – Read Text File Line by Line

To read a text file line by line in Kotlin, you can use BufferedReader class from the java.io package.

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

Steps to read a text file line by line

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

  1. Import BufferedReader and FileReader classes from the java.io package.
  2. Given a string value in the filePath variable with the path to your text file.
  3. Inside the try block, create a BufferedReader by passing a FileReader that reads from the file specified by filePath.
  4. Use a while loop to read the file line by line. The loop continues until there are no more lines to read.
  5. Inside the loop, you can process each line as needed.
  6. Finally, close the BufferedReader in a finally block to ensure that the file is properly closed, whether an exception is thrown or not.

Example Program to read ‘example.txt’ line by line

In this example, we have a text file example.txt which we read the contents line by line.

Main.kt

import java.io.BufferedReader
import java.io.FileReader

fun main() {
    val filePath = "example.txt" // Replace with the path to your text file
    var reader: BufferedReader? = null

    try {
        reader = BufferedReader(FileReader(filePath))
        var line: String?

        while (reader.readLine().also { line = it } != null) {
            // Process each line
            println(line)
        }
    } catch (e: Exception) {
        println("An error occurred: ${e.message}")
    } finally {
        try {
            reader?.close()
        } catch (e: Exception) {
            println("An error occurred while closing the file: ${e.message}")
        }
    }
}

Output

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 line by line using BufferedReader class, with a well detailed step by step process, and an example program.