Kotlin write file with BufferedWriter

BufferedWriter writes text to a character-output stream, buffering characters to provide for more efficient writing of single characters, arrays, and strings.

Kotlin write a file with BufferedWriter

The example writes two lines to a file with BufferedWriter.
import java.io.File

fun main(args: Array<String>) {

    val fileName = "src/resources/myfile.txt"
    val myfile = File(fileName)

    myfile.bufferedWriter().use { out ->

        out.write("First line\n")
        out.write("Second line\n")
    }

    println("Writed to file")
}
The bufferedWriter() returns a BufferedWriter for writing the content to the file. The use() method executes the given block function on the file and then closes it -
myfile.bufferedWriter().use { out ->

Comments