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 robustjava.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 importjava.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
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
5. Reading a File
To read a small file into a single String variable, use.readText().
kotlin
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
7. Mini Project: Notes Manager
Let's build a simple CLI application that asks the user for a note and appends it to anotes.txt file securely.
kotlin
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 atry-catchblock.
9. Best Practices
-
Use
forEachLinefor CSVs: If you are reading a database dump or a CSV file, always default toforEachLineorbufferedReader().useLines {}to keep your memory footprint extremely small.
10. Exercises
- 1. Write a program that asks the user for their Name and Age.
-
2.
Format a string:
"User: [Name], Age: [Age]".
-
3.
Use
appendText()to save it tousers.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?
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.