Sling Academy
Home/Kotlin/How to Read Text Files in Kotlin Using `File`

How to Read Text Files in Kotlin Using `File`

Last updated: November 30, 2024

Reading text files is a common task when you're working with data in Kotlin. Kotlin's standard library comes with comprehensive file manipulation capabilities, thanks to the java.io.File functionality that it builds upon. In this article, we'll demonstrate how to read text from files using the File class and explore different methods to suit your needs.

1. Reading a File Line by Line

When you want to read a file line by line, the readLines() function is an ideal choice. It reads all lines from a file and returns them as a list of strings.

import java.io.File

fun main() {
    val fileName = "example.txt"
    val lines: List<String> = File(fileName).readLines()

    lines.forEach { line ->
        println(line)
    }
}

In this snippet, we open example.txt, read all its lines at once, and print them out. The readLines() function is simple and effective for smaller files.

2. Reading a File into a Single String

If you're dealing with file contents where lines don't matter but the entire text does, consider using readText() to read the file into a single string:

import java.io.File

fun main() {
    val fileName = "example.txt"
    val content: String = File(fileName).readText()

    println(content)
}

This method is optimal when you need to treat the file as a whole, such as processing data or searching for occurrences within the text.

3. Reading Large Files with a Buffer

Handling large files efficiently might require reading files with buffered streams. Kotlin offers bufferedReader() for this purpose:

import java.io.File

fun main() {
    val fileName = "example.txt"
    File(fileName).bufferedReader().use { reader ->
        reader.forEachLine { line ->
            println(line)
        }
    }
}

Using bufferedReader() here allows you to handle large files by reading the contents into memory in chunks, rather than all at once. This method is efficient for applications working with big data or streams.

Conclusion

Kotlin makes reading text files straightforward with its clear and concise APIs. Whether you handle small or large files, these methods provide a toolkit for safe and efficient file operations. Depending on your requirements, choose the appropriate method to ensure your code remains scalable and performant.

Next Article: Writing to Text Files with Kotlin’s `File` API

Previous Article: Introduction to File Handling in Kotlin

Series: Kotlin - File & OS

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin