Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 08 / Topic 2 of 7

Writing text: writeText() vs appendText()

writeText() replaces the entire file with the given string, creating it if it doesn't exist yet. appendText() adds to whatever is already there, leaving it untouched.

val diary = File("diary.txt")

diary.writeText("Day 1: started the Kotlin course.\n")
println("After writeText: ${diary.readText()}")

// writeText REPLACES the whole file -- the line above is gone
diary.writeText("Day 2: files and text processing.\n")
println("After second writeText: ${diary.readText()}")

// appendText adds to the end without touching what's already there
diary.appendText("Day 3: still going strong.\n")
println("After appendText: ${diary.readText()}")
After writeText: Day 1: started the Kotlin course.

After second writeText: Day 2: files and text processing.

After appendText: Day 2: files and text processing.
Day 3: still going strong.

Real-world example: writeText() fits "save the current state" (a settings file, this part's to-do list); appendText() fits "record one more event without touching history" (a log file, this part's log parser).

Full program: examples/02_writing_text.kt.

Done here? The practice set for Part 8 — including the solutions — is on the part page.

Search the guide