I'm new to Kotlin, but I have a strong Java background (Java is my day job). I'm loving some of the shortcut functions in Kotlin. One of the big ones is File.appendText(). It's very convenient, in my opinion.
My question is about closing resources. If I was to use a writer, I would do something like this:
out8.writer().use { ... }
But I don't see any thing directly on the appendText method that indicates closing resources. Does Kotlin handle this behind the scenes for me, or is this something I have to worry about in another way?
You can just jump into the implementation of appendText
in your IDE to find out (Ctrl + B
on Windows, ⌘B
on Mac).
Here's the implementation of the method:
public fun File.appendText(text: String, charset: Charset = Charsets.UTF_8): Unit
= appendBytes(text.toByteArray(charset))
And here's the appendBytes
method that it delegates the work to:
public fun File.appendBytes(array: ByteArray): Unit
= FileOutputStream(this, true).use { it.write(array) }
You can see that it actually uses the use
helper method as you've expected.
You are right there is no appendText
function on Writer
, you can see here as further.
The use function is same as java-7 try-with-resource expression. it will close the resource after the block exit. In fact, File#appendText call the use function to close the resource.
IF you append the text only once you can using File#appendText instead. for example:
out8.appendText("content")
IF you want to operate a file more than once, you should using the File#bufferedWriter() instead, since the File#appendText will create & open a new writer each time. for example:
out8.bufferedWriter().use{
it.append("first").append("second")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With