javakotlinfilestreamkotlin-extension

How to close input or output stream when using Kotlin File's extensions


Do we need to close input or output stream when we use Kotlin's File.readText or File.writeText extensions

file.readText()
file.writeText("something")

Solution

  • The readText and writeText methods call the use method on the Input and OutputStream. (See: https://github.com/JetBrains/kotlin/blob/30788566012c571aa1d3590912468d1ebe59983d/libraries/stdlib/jvm/src/kotlin/io/FileReadWrite.kt#L108)

    According to the documentation this method automatically closes the object afterwards. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/use.html

    So there is no need to close it manually.