Kotlin
appendText
Learn to append to files with File.appendText.
appendText: Append to the end
appendText(text) adds the given string to the end of the file; it preserves the existing content. Unlike writeText it does not overwrite. If the file does not exist it is created. This is ideal for log files or accumulated records.
val f = File("gunluk.txt")
f.writeText("start")
f.appendText(" - more")
println(f.readText()) // start - more
Each appendText call opens the file, writes to the end and closes it. Very frequent appends can affect performance; in that case batching and writing once is more efficient. To add lines it is common to append \n at the end of the string.
The log pattern
appendText is common in programs that keep logs. Each event is appended as a line to the file; \n separates the lines. The file grows but old records are preserved.
val log = File("event.txt")
log.appendText("login\n")
log.appendText("logout\n")
println(log.readText())
Here two events accumulate on separate lines. Each appendText call adds one line. Log files usually start with a timestamp; later you will learn to produce these stamps with LocalDate and LocalTime. For large logs rotation (splitting the file) may also be considered.
Exercise Accumulate three pieces
Create val f = File("kayit.txt"). Start with f.writeText("a"). Append twice with f.appendText("b") and f.appendText("c"). Read and print with println(f.readText()). Add the import java.io.File import.
Show example solution
fun main() {
val f = File("kayit.txt")
f.writeText("a")
f.appendText("b")
f.appendText("c")
println(f.readText())
}
Test yourself
-
How does appendText differ from writeText?
- It appends to the end instead of overwriting
- It deletes the file
- It creates a new file
- It makes the file read-only
Show answer
It appends to the end instead of overwriting — appendText preserves the existing content and adds to the end.
-
Append to the end
f.____("extra line")
Show answer
f.appendText("extra line")
-
Match the appendText concepts
- appendText(text)
- Appends to end
- existing content
- Preserved
- \n
- Line break
- log pattern
- Accumulates events
Next lesson: Summary - File I/O