0
0
KotlinHow-ToBeginner · 3 min read

How to Read File in Kotlin: Simple Examples and Tips

In Kotlin, you can read a file easily using File("filename").readText() to get the whole content as a string or File("filename").readLines() to get a list of lines. These methods come from Kotlin's standard library and require importing java.io.File.
📐

Syntax

To read a file in Kotlin, you use the File class from java.io. The main methods are:

  • readText(): Reads the entire file content as a single string.
  • readLines(): Reads the file and returns a list of strings, each representing a line.

You create a File object by passing the file path as a string.

kotlin
import java.io.File

val content: String = File("path/to/file.txt").readText()
val lines: List<String> = File("path/to/file.txt").readLines()
💻

Example

This example shows how to read a file named example.txt and print its content and lines separately.

kotlin
import java.io.File

fun main() {
    val filePath = "example.txt"

    // Read whole file as text
    val text = File(filePath).readText()
    println("File content as text:")
    println(text)

    // Read file as list of lines
    val lines = File(filePath).readLines()
    println("\nFile content as lines:")
    for (line in lines) {
        println(line)
    }
}
Output
File content as text: Hello Kotlin This is a file. Reading files is easy. File content as lines: Hello Kotlin This is a file. Reading files is easy.
⚠️

Common Pitfalls

Common mistakes when reading files in Kotlin include:

  • Not importing java.io.File.
  • Using incorrect file paths, causing FileNotFoundException.
  • Not handling exceptions when the file does not exist or is unreadable.
  • Confusing readText() (whole content) with readLines() (list of lines).

Always ensure the file path is correct and consider using try-catch to handle errors gracefully.

kotlin
import java.io.File

fun main() {
    val filePath = "missing.txt"
    try {
        val text = File(filePath).readText()
        println(text)
    } catch (e: Exception) {
        println("Error reading file: ${'$'}{e.message}")
    }
}
Output
Error reading file: missing.txt (No such file or directory)
📊

Quick Reference

Here is a quick summary of file reading methods in Kotlin:

MethodDescription
readText()Reads entire file content as a single string.
readLines()Reads file content as a list of lines.
File(path)Creates a File object for the given path.
try-catchUse to handle exceptions when reading files.

Key Takeaways

Use File(path).readText() to read the whole file as a string.
Use File(path).readLines() to read the file line by line as a list.
Always import java.io.File to work with files.
Handle exceptions with try-catch to avoid crashes if the file is missing.
Check your file path carefully to avoid common errors.