How to write content to file in Kotlin

We are going to learn to write content to file in Kotlin using the extension functions provided by Kotlin (or say idiomatic way or Kotlin way). You may also use the existing Java code that writes content to a file.

In this Kotlin Tutorial, we shall go through an example of how to use Java Classes like PrintWriter to write to a file, and more examples using extension functions in Kotlin style.

Example using PrintWriter to write content to file in Kotlin

Example using extension function java.io.File.printWriter() to write content to file

Example using extension function java.io.File.bufferedWriter() to write content to file

Example using extension function java.io.File.writeText() to exclusively write text to file

Conclusion :

We have learn to write content to file in Kotlin using standard Java function and also using Kotlin extension functions to java.io.File : printWriter(), bufferedWriter(), writeText(). Documentation for these extension functions could be found here.