Kotlin Files.writeString
Write the word oats to an isolated temporary file and read it back to check what was saved.
A simple example
Files.writeString
- Start with Empty file and the letter A
- Do this Write the text, then read it
- Result "A"
Syntax
Files.writeString(path, "oats")
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarSave an item to a grocery note
A small application saves a human-readable note for the next time it opens. Choose the text encoding and read or write the file deliberately so the saved characters can be recovered as intended.
import java.nio.file.Files
fun main() {
val path = Files.createTempFile("receipt", ".txt")
try {
Files.writeString(path, "oats")
println(Files.readString(path))
} finally {
Files.deleteIfExists(path)
}
}
oats
Reading oats back confirms that the four letters reached the file. The example cleans up the temporary storage when it finishes.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Save the note and read it back before the desk closes. Which characters are recovered?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Save the note and read it back before the desk closes. Which characters are recovered?
What to watch for
Opening an existing path in write mode may truncate its contents. Choose append mode when earlier notes must be preserved.