CodeBlanks Logo Icon CodeBlanks

Summary - File I/O

Combine readText, writeText and readLines to write a notes app.

Summary - File I/O

In this group you learned the file path with java.io.File, reading all content with readText, overwriting with writeText, getting a list of lines with readLines and appending to the end with appendText.

Now you will combine them: first write to a file and walk the lines with readLines, then use writeText and appendText together. This structure is the foundation of small file-based applications in Kotlin. Later, formats such as JSON and CSV are built on top of these methods.

Practice Combine writeText and readLines

Create val f = File("liste.txt"). Write three lines with f.writeText("apple\npear\nbanana"). Read the lines with val lines = f.readLines(). Print the count with println(lines.size); then loop with for (line in lines) and println each line. Add the import java.io.File import.

Starter code

Main.kt
import java.io.File

// File object for path liste.txt
// write three fruit lines with writeText
// read with readLines, print size then each line
fun main() {
    // write here
}

Sample solution

Main.kt
fun main() {
    val f = File("liste.txt")
    f.writeText("apple\npear\nbanana")
    val lines = f.readLines()
    println(lines.size)
    for (line in lines) println(line)
}

Expected output

3
apple
pear
banana

Practice Combine writeText and appendText

Create val f = File("gunluk.txt"). Start with f.writeText("start"). Append with f.appendText(" - more"). Read and print with println(f.readText()). Add the import java.io.File import.

Starter code

Main.kt
import java.io.File

// File object for path gunluk.txt
// start with writeText("start")
// append with appendText(" - more")
// read with readText and println
fun main() {
    // write here
}

Sample solution

Main.kt
fun main() {
    val f = File("gunluk.txt")
    f.writeText("start")
    f.appendText(" - more")
    println(f.readText())
}

Expected output

start - more

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which overwrites a file?

  • readText
  • writeText Correct answer
  • appendText
  • readLines

Explanation: writeText erases the existing content and writes the new one.

2 Match the file methods

Term Meaning
File("a.txt") Path representation
readText() Reads all content
writeText() Overwrites
appendText() Appends to end

All lessons in Intermediate