appendText
- Kotlin course
- Intermediate
- Lesson 98/116
- 5 min
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 - moreEach 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.
Practice 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.
Starter code
import java.io.File
// File object for path kayit.txt
// start with writeText("a")
// append "b" and "c" with appendText
// read with readText and println
fun main() {
// write here
}Sample solution
fun main() {
val f = File("kayit.txt")
f.writeText("a")
f.appendText("b")
f.appendText("c")
println(f.readText())
}Expected output
abc
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does appendText differ from writeText?
- It appends to the end instead of overwriting Correct answer
- It deletes the file
- It creates a new file
- It makes the file read-only
Explanation: appendText preserves the existing content and adds to the end.
2 Append to the end
f.____("extra line")
f.appendText("extra line")
Explanation: appendText adds the given string to the end of the file.
3 Match the appendText concepts
| Term | Meaning |
|---|---|
appendText(text) |
Appends to end |
existing content |
Preserved |
\n |
Line break |
log pattern |
Accumulates events |