Part 08 / Stage 1
Files, text and data formats
Goal: Check and create files with
java.io.File, write and read text with Kotlin's stdlib extensions, close readers/writers safely withuse {}, turn a list of objects into simple comma-separated text and back, and use all of it to build a to-do list that survives between runs and a small log parser. Time: ~5 hours · Level: comfortable with classes (Part 7) and collections (Part 6)
What you will learn
java.io.File: checking whether a pathexists(), telling a file from a directory,mkdirs()to create folders, and the handful of properties everyFilecarries- Writing text:
writeText()(replaces the whole file) versusappendText()(adds to the end) - Reading text:
readText()(oneString),readLines()(aList<String>), andforEachLine()(stream through a file one line at a time, without loading it all at once) use {}: closing aBufferedReader/BufferedWriterautomatically, even when the block throws -- proved, not assumed, the same way Part 6 provedmapOfkeeps insertion order- Simple structured text: building comma-separated rows with
joinToString, parsing them back withsplit, and why this naive approach breaks once a field itself contains the delimiter - Building a to-do list whose tasks are saved to a text file, loaded back the next time the program runs
- Building a small log parser that reads real-looking log lines, counts them by level, and skips (without crashing on) lines that don't parse
Topics in this part
Practice
Try each one yourself first. Then check the solution.
Every exercise is one file with a top-level fun main(), using what Parts 1-8 have covered so
far: val/var, basic types, null safety, control flow, functions, collections, classes, and
this part's File/use {}/text reading and writing. Every exercise cleans up the files it
creates at the end, so running it twice in a row behaves the same way both times.
Exercise 1: Save and read back a note
Scenario: the simplest possible round trip -- write one line to a file, then read it straight
back.
What to do: write val note = File("note.txt"), use writeText(...) to save "Welcome to Kotlin file I/O.", then print whether the file exists() and its readText() content.
Sample output:
Exists: true
Content: Welcome to Kotlin file I/O.
💡 Hint: File("note.txt") doesn't create anything by itself -- it's writeText(...) that
actually creates the file on disk.
Exercise 2: Build a list with appendText
Scenario: a grocery list is built up one item at a time, across three separate calls, not
written all at once.
What to do: write val groceries = File("groceries.txt"), call appendText(...) three
times to add "Rice\n", "Dal\n", "Atta\n" one at a time, then readLines() the file and
print the count and the list.
Sample output:
Items (3): [Rice, Dal, Atta]
💡 Hint: if you run this more than once without deleting groceries.txt first, appendText
keeps adding -- delete the file (or check exists()) before the first appendText call if you
want a clean start every time.
Exercise 3: Parse comma-separated contacts
Scenario: a small contacts export has one person per line, fields separated by commas.
What to do: write a file containing "Asha,29,Pune\nRavi,34,Mumbai\nMeera,26,Bengaluru\n"
using writeText, then read it back line by line, split(",") each line, and print
"$name is $age years old and lives in $city" for each.
Sample output:
Asha is 29 years old and lives in Pune
Ravi is 34 years old and lives in Mumbai
Meera is 26 years old and lives in Bengaluru
💡 Hint: val (name, age, city) = line.split(",").map { it.trim() } destructures the
3-element list straight into three names, the same trick Part 6 used on map entries.
Exercise 4: Prove use {} closes on the way out
Scenario: section 4's README showed use {} closing a writer even when the block throws.
Reproduce that yourself, with an attendance roll call instead of a shipping log.
What to do: inside a try, open File("attendance.txt").bufferedWriter().use { ... },
write "Asha: present" and "Ravi: present" (each followed by writer.newLine()), then
throw RuntimeException("roll call interrupted"). Catch it outside and print its message. Then
reopen the file with bufferedReader().use { ... } and print every line with forEachLine.
Sample output:
Caught: roll call interrupted
File content after the exception:
Asha: present
Ravi: present
💡 Hint: the line you write right after the throw (if you add one, to double check) never
runs -- throw hands control straight to the nearest matching catch, skipping everything
after it in the use {} block, but use {} still closes the writer before that happens.
Exercise 5: A small book catalog, round-tripped through CSV
Scenario: a personal reading tracker keeps title, author and page count for each book, and
needs to survive being saved and reloaded.
What to do: write class Book(val title: String, val author: String, val pages: Int) with
a toCsvLine() method, build a list of 3 books, write them to File("books.csv"), read the
file back, parse each line into a Book, print "$title by $author ($pages pages)" for each,
and print the total page count across all three.
Sample output:
The Alchemist by Paulo Coelho (208 pages)
Wings of Fire by A.P.J. Abdul Kalam (180 pages)
Sapiens by Yuval Noah Harari (443 pages)
Total pages: 831
💡 Hint: books.joinToString("\n") { it.toCsvLine() } builds every line in one call --
no separate loop needed to assemble the file content.
Exercise 6: Attendance log with broken lines
Scenario: a roll-call export has one status|name line per student, but one line in the
middle is corrupted and must not stop the count.
What to do: write a file with these lines, in this order: "present|Asha",
"absent|Ravi", "present|Meera", "this entry is broken", "present|Karan",
"absent|Nisha". Read it with forEachLine, counting present and absent, skipping (and
printing) any line that isn't exactly "present|..." or "absent|...", without crashing.
Sample output:
Skipped: "this entry is broken"
Present: 3, Absent: 2, Skipped: 1
💡 Hint: line.split("|", limit = 2) followed by checking parts.size == 2 && parts[0] in setOf("present", "absent") tells a well-formed line from a broken one without
needing a try/catch for this particular check.
Exercise 7: Sales report written to a reports/ folder
Scenario: a shop's daily sales export needs to become a per-item revenue summary, saved
into a reports/ folder that might not exist yet.
What to do: write a sales.csv-shaped file with lines "Rice (kg),5,68.0",
"Dal (kg),2,145.0", "Rice (kg),3,68.0", "Atta (kg),4,52.0" (item, quantity, price). Parse
each line, accumulate quantity x price per item into a mutableMapOf<String, Double>, create
a reports/ directory with mkdirs() if it doesn't exist, write "$item: ₹$revenue" per line
into reports/summary.txt using bufferedWriter().use { ... }, then read that file back and
print it.
Sample output:
reports/ exists: true
--- reports/summary.txt ---
Rice (kg): ₹544.0
Dal (kg): ₹290.0
Atta (kg): ₹208.0
💡 Hint: revenueByItem[item] = (revenueByItem[item] ?: 0.0) + lineTotal is the same
"update or insert" pattern as Part 6's shopping cart and Part 7's transaction log -- read what's
there (or 0.0 for a new item), add, write it back.
Show the solutions for Part 8 (7 files)
solutions/ex01.kt
import java.io.File
fun main() {
val note = File("note.txt")
note.writeText("Welcome to Kotlin file I/O.")
println("Exists: ${note.exists()}")
println("Content: ${note.readText()}")
note.delete()
}
solutions/ex02.kt
import java.io.File
fun main() {
val groceries = File("groceries.txt")
if (groceries.exists()) groceries.delete()
groceries.appendText("Rice\n")
groceries.appendText("Dal\n")
groceries.appendText("Atta\n")
val items = groceries.readLines()
println("Items (${items.size}): $items")
groceries.delete()
}
solutions/ex03.kt
import java.io.File
fun main() {
val contacts = File("contacts.txt")
contacts.writeText("Asha,29,Pune\nRavi,34,Mumbai\nMeera,26,Bengaluru\n")
for (line in contacts.readLines()) {
val fields = line.split(",").map { it.trim() }
val (name, age, city) = fields
println("$name is $age years old and lives in $city")
}
contacts.delete()
}
solutions/ex04.kt
import java.io.File
fun main() {
val attendance = File("attendance.txt")
try {
attendance.bufferedWriter().use { writer ->
writer.write("Asha: present")
writer.newLine()
writer.write("Ravi: present")
writer.newLine()
throw RuntimeException("roll call interrupted")
@Suppress("UNREACHABLE_CODE")
writer.write("Meera: present")
}
} catch (e: RuntimeException) {
println("Caught: ${e.message}")
}
println("File content after the exception:")
attendance.bufferedReader().use { reader ->
reader.forEachLine { println(" $it") }
}
attendance.delete()
}
solutions/ex05.kt
import java.io.File
class Book(val title: String, val author: String, val pages: Int) {
fun toCsvLine(): String = listOf(title, author, pages.toString()).joinToString(",")
}
fun parseBookLine(line: String): Book {
val fields = line.split(",").map { it.trim() }
require(fields.size == 3) { "expected 3 fields, got ${fields.size}" }
return Book(fields[0], fields[1], fields[2].toInt())
}
fun main() {
val books = listOf(
Book("The Alchemist", "Paulo Coelho", 208),
Book("Wings of Fire", "A.P.J. Abdul Kalam", 180),
Book("Sapiens", "Yuval Noah Harari", 443)
)
val booksFile = File("books.csv")
booksFile.writeText(books.joinToString("\n") { it.toCsvLine() } + "\n")
val parsed = booksFile.readLines().map { parseBookLine(it) }
for (book in parsed) {
println("${book.title} by ${book.author} (${book.pages} pages)")
}
val totalPages = parsed.sumOf { it.pages }
println("Total pages: $totalPages")
booksFile.delete()
}
solutions/ex06.kt
import java.io.File
fun main() {
val attendanceFile = File("roll_call.txt")
attendanceFile.writeText(
listOf(
"present|Asha",
"absent|Ravi",
"present|Meera",
"this entry is broken",
"present|Karan",
"absent|Nisha"
).joinToString("\n") + "\n"
)
var present = 0
var absent = 0
var skipped = 0
attendanceFile.forEachLine { line ->
val parts = line.split("|", limit = 2)
if (parts.size != 2 || parts[0] !in setOf("present", "absent")) {
skipped++
println("Skipped: \"$line\"")
return@forEachLine
}
if (parts[0] == "present") present++ else absent++
}
println("Present: $present, Absent: $absent, Skipped: $skipped")
attendanceFile.delete()
}
solutions/ex07.kt
import java.io.File
class SaleLine(val item: String, val quantity: Int, val price: Double)
fun parseSaleLine(line: String): SaleLine {
val fields = line.split(",").map { it.trim() }
require(fields.size == 3) { "expected 3 fields, got ${fields.size}" }
return SaleLine(fields[0], fields[1].toInt(), fields[2].toDouble())
}
fun main() {
val salesFile = File("sales.csv")
salesFile.writeText(
listOf(
"Rice (kg),5,68.0",
"Dal (kg),2,145.0",
"Rice (kg),3,68.0",
"Atta (kg),4,52.0"
).joinToString("\n") + "\n"
)
val sales = salesFile.readLines().map { parseSaleLine(it) }
val revenueByItem = mutableMapOf<String, Double>()
for (sale in sales) {
val lineTotal = sale.quantity * sale.price
revenueByItem[sale.item] = (revenueByItem[sale.item] ?: 0.0) + lineTotal
}
val reportsDir = File("reports")
reportsDir.mkdirs()
println("reports/ exists: ${reportsDir.exists()}")
val summaryFile = File(reportsDir, "summary.txt")
summaryFile.bufferedWriter().use { writer ->
for ((item, revenue) in revenueByItem) {
writer.write("$item: ₹$revenue")
writer.newLine()
}
}
println("--- reports/summary.txt ---")
summaryFile.bufferedReader().use { reader ->
reader.forEachLine { println(it) }
}
summaryFile.delete()
salesFile.delete()
reportsDir.delete()
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Calling writeText() when you meant to add a line |
It silently replaces the entire file's content, losing everything written before | Use appendText() for "add to what's there"; reserve writeText() for "this is the full, current content" |
Treating readLines() as safe for any file size |
It loads the whole file into memory as a List<String> before you see a single line |
Use forEachLine() for a file that could be large, or that you only need to scan once |
Opening a BufferedReader/BufferedWriter without use {} |
The file handle stays open until the garbage collector happens to clean it up -- not guaranteed to happen promptly, or at all before the program needs that handle again | Wrap every bufferedReader()/bufferedWriter() call in use { ... } |
Splitting CSV-ish text on "," when a field might contain a comma |
"Rice, 1kg pack".split(",") gives two fields, not the one you meant |
Pick a delimiter that genuinely won't appear in the data (this part uses a pipe character for exactly that reason), or reach for a real CSV library once one is available (Stage 2 onward) |
| Letting one bad line crash a whole file's worth of parsing | A single malformed row throws, and an uncaught exception stops the loop for every row after it too | Wrap each line's parsing in its own try/catch, as the log parser does, so one bad line is skipped, not fatal |
| Assuming a file that doesn't exist yet is an error | The very first run of a program like the to-do list has nothing to load -- that's normal | Check file.exists() and return an empty starting point instead of trying to read a file that isn't there |
Forgetting readLines() strips newline characters already |
Manually stripping \n again, or expecting a trailing \n to show up as an empty extra line, leads to off-by-one bugs |
Trust readLines()'s contract: one String per line, no line-ending characters included |
Quick recap
File(path)is just a handle --exists(),isFile,isDirectoryandmkdirs()tell you and change what's actually on disk.writeText()replaces a file's whole content;appendText()adds to the end.readText()gives oneString;readLines()gives aList<String>;forEachLine()streams through without holding the whole file in memory.use {}closes aBufferedReader/BufferedWritereven when the block throws -- proved with a deliberate exception, not assumed.joinToString/splitbuild and parse simple delimiter-separated text; pick a delimiter the data genuinely won't contain.- Wrapping each line's parsing in its own
try/catchturns "one bad line" into a skip, not a crash. - Rewriting the whole file after every change (rather than editing one line in place) is the standard, simple way to persist a small amount of state to a text file.
Checklist
- I checked whether a file exists, created one with
writeText(), and created a directory withmkdirs(). - I proved to myself that
writeText()replaces a file's content whileappendText()adds to it. - I read the same file back with
readText(),readLines()andforEachLine(), and can say when to reach for each one. - I wrapped a
bufferedReader()/bufferedWriter()inuse {}, and watched a deliberate exception inside the block still leave already-written content safely on disk. - I built and parsed a simple comma-separated file of my own objects.
- I built the to-do list myself and ran it twice, proving a task saved in the first run was still there at the start of the second.
- I built the log parser myself, including the line that doesn't parse, and watched it get skipped instead of crashing the program.