Title here
Summary here
Here’s the translation of the Go code for writing files to Kotlin, along with explanations in Markdown format suitable for Hugo:
Writing files in Kotlin follows similar patterns to the ones we saw earlier for reading.
import java.io.File
import java.io.BufferedWriter
fun check(e: Exception?) {
if (e != null) {
throw e
}
}
fun main() {
// To start, here's how to dump a string (or just bytes) into a file.
val d1 = "hello\nkotlin\n".toByteArray()
try {
File("/tmp/dat1").writeBytes(d1)
} catch (e: Exception) {
check(e)
}
// For more granular writes, open a file for writing.
val f = File("/tmp/dat2").bufferedWriter()
// It's idiomatic to use `use` for automatic resource management
f.use { writer ->
// You can write byte arrays as you'd expect.
val d2 = byteArrayOf(115, 111, 109, 101, 10)
writer.write(String(d2))
println("wrote ${d2.size} bytes")
// A write method for strings is also available.
val n3 = writer.write("writes\n")
println("wrote $n3 bytes")
// BufferedWriter provides buffered writing.
writer.write("buffered\n")
println("wrote ${"buffered\n".length} bytes")
// The `use` function automatically calls flush and close
}
}
Try running the file-writing code.
$ kotlin writing-files.kt
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes
Then check the contents of the written files.
$ cat /tmp/dat1
hello
kotlin
$ cat /tmp/dat2
some
writes
buffered
Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin
and stdout
streams.