Kotlin

Write to a File

admin by @admin ADMIN
8m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`writeText` overwrites; `appendText` appends. For multiple writes, use `bufferedWriter().use { }` for efficiency + auto-close.
Kotlin
Raw
import java.io.File

fun main() {
    val log = File("/tmp/app.log")

    // Whole text in one go
    log.writeText("startup at ${System.currentTimeMillis()}\n")

    // Append individual lines
    log.appendText("user signed in\n")
    log.appendText("user signed out\n")

    // For many writes — buffer + auto-close via `use { }`
    log.bufferedWriter().use { w ->
        repeat(10) { i ->
            w.write("line $i")
            w.newLine()
        }
    }

    // Atomic write (rename pattern): write to .tmp, then rename
    val tmp = File("/tmp/state.json.tmp")
    val target = File("/tmp/state.json")
    tmp.writeText("""{"ready": true}""")
    tmp.renameTo(target)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.