This article covers different ways to write data to a text file in Kotlin. The solution should truncate the file before writing or create a new file if it doesn’t exist.

1. Using File.writeText() function

The standard approach to set the file’s content is with the File.writeText() function. The data is encoded using the default UTF-8 or the specified charset.

Download Code

2. Using PrintWriter

The PrintWriter is the recommended class that requires writing characters rather than bytes.

Download Code

3. Using Files.newBufferedWriter() function

The Files.newBufferedWriter() function returns a BufferedWriter that may be used to write text to the file efficiently.

Download Code

4. Using OutputStreamWriter

Since FileOutputStream is meant for writing streams of bytes, you can construct an OutputStreamWriter for writing streams of characters. To improve efficiency, it is advisable to wrap a BufferedWriter around OutputStreamWriter.

Download Code

5. Using FileWriter

The FileWriter is a convenience class for writing streams of characters using default character encoding. We can use this as:

Download Code

6. Using File.bufferedWriter() function

It is advisable to wrap BufferedWriter around file writer as its write operations are very costly. We can do this with the File.bufferedWriter() function, which returns a new BufferedWriter for writing this file’s content.

Download Code

7. Using PrintStream

A PrintStream can be used to add functionality to an output stream. But all characters printed by a PrintStream are converted into bytes using the platform’s default character encoding.

Download Code

That’s all about writing to a file in Kotlin.