writeText
- Kotlin course
- Intermediate
- Lesson 96/116
- 5 min
Learn to write files with File.writeText.
writeText: Write to a file
writeText(text) writes the given string to the file. If the file does not exist it is created; if it exists, its content is completely overwritten. So the old content is lost. To append to the end use appendText (next lesson).
val f = File("member.txt")
f.writeText("Alex")
f.writeText("Sam") // file now contains only "Sam"The second writeText overwrites the first; the file ends up with only the last content. If you do not want this behavior use appendText. writeText uses UTF-8 encoding.
Creating a new file
writeText automatically creates a new file if it does not exist. If the parent directories do not exist it throws an exception; so it is safe to create them first with f.parentFile?.mkdirs(). If the file already exists only the content changes; the file metadata (permissions etc.) is preserved.
val f = File("data/output.txt")
f.parentFile?.mkdirs()
f.writeText("ready")Here if the data directory does not exist it is created first, then the file is written. ?.mkdirs() is a safe call; if parentFile is null it does nothing. This pattern is common in programs that produce file output.
Practice Write a two-line file and read it
Create val f = File("not.txt"). Write two lines with f.writeText("line 1\nline 2") (use \n inside the string). Read it back with println(f.readText()). Add the import java.io.File import.
Starter code
import java.io.File
// File object for path not.txt
// write "line 1\nline 2" (two lines) to it
// read with readText and println
fun main() {
// write here
}Sample solution
fun main() {
val f = File("not.txt")
f.writeText("line 1\nline 2")
println(f.readText())
}Expected output
line 1 line 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if writeText is called on an existing file?
- Appends to the end
- Throws an exception
- Overwrites the content Correct answer
- Ignores the call
Explanation: writeText erases the old content and writes the new one.
2 Match the writeText concepts
| Term | Meaning |
|---|---|
writeText(text) |
Overwrites |
overwrite |
Erases old content |
UTF-8 |
Encoding |
appendText |
Appends (not overwrite) |
3 Write to the file
f.____("new content")
f.writeText("new content")
Explanation: writeText writes the given string to the file.