Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: appendText and closing resources

Tags:

java

kotlin

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?

like image 813
craigmiller160 Avatar asked Jul 25 '17 19:07

craigmiller160


2 Answers

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.

like image 79
zsmb13 Avatar answered Nov 14 '22 15:11

zsmb13


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") 
}
like image 38
holi-java Avatar answered Nov 14 '22 14:11

holi-java