Kotlin – Write to File

You can write to a file in Kotlin programming language. Usually a string or data is written to a file.

One can write to file in Kotlin using the extension functions provided by Kotlin (or say idiomatic way or Kotlin way) or 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 –  Write to File with PrintWriter

In this example, we take a string and write it to a file using java.io.PrintWriter. Following are the steps.

  1. Have your data ready as a string in a variable.
  2. Initialize a PrintWriter object.
  3. Append the string to the file using PrintWriter.append() function.
  4. Close the writer.

A new file with the name file.txt, as specified for the argument of PrintWriter(), shall be created with the content. If the file is already present, the content of the file is cleared first, and then the new content is written into the file.

Example – Write to File with java.io.File.printWriter()

In this example, we shall use Kotlin extension function printWriter to the class java.io.File. Following is the process to write to file.

  1. Have your content as a string.
  2. Pass the file name to the File constructor.
  3. Then call printWriter() on the File.
  4. With use, call the println(content) on the writer which writes the content to the file.

Example – Write to File with java.io.File.bufferedWriter()

Similar to the previous example, we can use java.io.File.bufferedWriter() extension function to get the writer object and then use write() function on the writer object to write content to the file.

Example – Write to File with java.io.File.writeText()

If you are writing exclusively text to a File, then you can use the extension function java.io.File.writeText().

In the following example, we have used this extension function to write some text to a file.

Conclusion

In this Kotlin Tutorial, we learned to write content to file in Kotlin using standard Java function and also using Kotlin extension functions to java.io.File : printWriter(), bufferedWriter(), writeText().