Skip to main content
Kotlin Basics
CHAPTER 22 Beginner

File Handling in Kotlin

Updated: May 18, 2026
5 min read

# CHAPTER 22

File Handling in Kotlin

1. Chapter Introduction

Any application that needs to save user settings, log errors, or export data must interact with the operating system's file system. Because Kotlin runs on the JVM, it has full access to the robust java.io.File library. However, Kotlin provides incredible Extension Functions on top of Java's File API, turning a complex 20-line Java BufferedReader task into a single line of code!

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Import java.io.File.
  • Write text to a new file (writeText).
  • Append text to an existing file (appendText).
  • Read the entire contents of a file (readText).
  • Read a file line-by-line for large datasets (forEachLine).

3. Writing to a File

To interact with files, we must import java.io.File. To create a file and write data to it, use the .writeText() extension function. *Warning: If the file already exists, writeText() will completely overwrite it!*
kotlin
1234567891011
import java.io.File

fun main() {
    val fileName = "settings.txt"
    val file = File(fileName)
    
    // Writes the text and creates the file if it doesn't exist
    file.writeText("Theme=Dark\nVolume=80")
    
    println("File written successfully!")
}

4. Appending to a File

If you are building an error log, you don't want to overwrite the file; you want to add data to the end of it. Use .appendText().
kotlin
1234567891011
import java.io.File

fun main() {
    val file = File("logs.txt")
    
    // Adds text to the end of the file
    file.appendText("Error: Connection timeout at 10:00 AM\n")
    file.appendText("Error: Database locked at 10:05 AM\n")
    
    println("Logs appended!")
}

5. Reading a File

To read a small file into a single String variable, use .readText().
kotlin
12345678910111213
import java.io.File

fun main() {
    val file = File("settings.txt")
    
    // Check if the file exists before trying to read it!
    if (file.exists()) {
        val contents = file.readText()
        println("File Contents:\n$contents")
    } else {
        println("File not found!")
    }
}

6. Reading Large Files (Line by Line)

If a file is 5 Gigabytes, using .readText() will load all 5 GB into your RAM, crashing your app with an OutOfMemoryError. For large files, you must process them one line at a time using .forEachLine { }.
kotlin
123456789101112
import java.io.File

fun main() {
    val file = File("logs.txt")
    
    if (file.exists()) {
        // Reads one line into memory, processes it, and throws it away
        file.forEachLine { line ->
            println("READING: $line")
        }
    }
}

7. Mini Project: Notes Manager

Let's build a simple CLI application that asks the user for a note and appends it to a notes.txt file securely.
kotlin
12345678910111213141516171819
import java.io.File

fun main() {
    val file = File("my_notes.txt")
    
    print("Enter a note to save: ")
    val note = readln()
    
    try {
        // Append the note and add a newline
        file.appendText("$note\n")
        println("Note saved successfully!")
        
        println("\n--- ALL NOTES ---")
        println(file.readText())
    } catch (e: Exception) {
        println("Critical Error saving file: ${e.message}")
    }
}

8. Common Mistakes

  • Relative Path Confusion: If you just write File("data.txt"), where does it save? It saves in the "Current Working Directory", which is usually the root folder of your IntelliJ Project. If you run the code on a different machine, the path might break.
  • Forgetting try-catch: File I/O (Input/Output) is highly volatile. The hard drive might be full, or the user might lack permission. Always wrap critical file operations in a try-catch block.

9. Best Practices

  • Use forEachLine for CSVs: If you are reading a database dump or a CSV file, always default to forEachLine or bufferedReader().useLines {} to keep your memory footprint extremely small.

10. Exercises

  1. 1. Write a program that asks the user for their Name and Age.
  1. 2. Format a string: "User: [Name], Age: [Age]".
  1. 3. Use appendText() to save it to users.txt.

11. MCQs with Answers

Question 1

What Java class does Kotlin use to interact with the file system?

Question 2

Which extension function creates a file and writes text, overwriting any existing data?

Question 3

Which extension function adds data to the end of an existing file?

Question 4

What method safely checks if a file exists on the hard drive before you attempt to read it?

Question 5

Which function reads an entire file into a single String variable?

Question 6

What is the danger of using .readText() on a massive 10 GB log file?

Question 7

What function should you use to process a massive file safely?

Question 8

Why is it important to wrap File operations in a try-catch block?

Question 9

When using file.appendText("$note\n"), what does \n do?

Q10. Are Kotlin's file methods natively built from scratch, or are they Extension Functions built on top of the standard Java API? a) Built from scratch b) Extension Functions on top of the Java API Answer: b) Extension Functions on top of the Java API.

12. Interview Questions

  • Q: Compare .readText() and .forEachLine { }. When would you use one over the other?
  • Q: Explain why file operations must be handled with care regarding Exceptions.

13. Summary

Kotlin transforms the historically painful process of Java File I/O into a delightful experience. By providing extension functions like .writeText() and .readText(), saving data to disk takes only a single line of code. However, responsible developers must still respect the physical limits of hardware by utilizing try-catch blocks and line-by-line reading for large datasets.

14. Next Chapter Recommendation

File writing is slow. If your app writes a massive file, the entire app freezes until it finishes! To prevent freezing the User Interface, we must run slow tasks in the background. In Chapter 23: Coroutines in Kotlin, we will learn how to write Asynchronous, non-blocking code.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·