This post will discuss how to add text to the end of a file in Kotlin. The solution should append text to a file, not overwrite the existing data. If the file doesn’t exist, create it and write data.

There are numerous methods to add text at the end of a file in Kotlin:

1. Using Files.write() function

A simple and fairly efficient solution to call the Files.write() function to write text to a file with append mode since the default behavior of this function is to overwrite an existing file.

Download Code

 
The above solution does not create a new file if the target file doesn’t exist, but throws NoSuchFileException. To create a new file if the file doesn’t exist, we can pass the StandardOpenOption.CREATE option along with StandardOpenOption.APPEND.

Download Code

2. Using FileWriter

Another alternative is to get a FileWriter instance and write streams of characters into a file using its write() function. To add text at the end of the file rather than the beginning, pass the boolean value true as the second parameter to the FileWriter constructor.

Download Code

That’s all about adding text to the end of a file in Kotlin.