Learn how to append text to file in Kotlin using Kotlin’s extension function, File.appendText() a single line of code, with an example program.

There could be scenarios where you may need to add a debug line to the report, or some log file, etc. In such scenarios, Kotlin’s extension funtion to java.io.File, appendText(String text) helps to append text to the original file.

Append Text to File in Kotlin

Syntax :

fun File.appendText(
?text: String,
?charset: Charset = Charsets.UTF_8)

Usage :



String filenameRequiredName of the text file to which textToBeAppended is appended.
String textToBeAppendedRequiredThe string which is appended to the specified file.
Charset charsetOptionalThe default Charset used is Charsets.UTF_8. You may specify any other Charset if required.

Example Kotlin Program

Original Contents of file

Hello World. Welcome to Kotlin Tutorial by www.tutorialkart.com.

After execution of the program

Hello World. Welcome to Kotlin Tutorial by www.tutorialkart.com. This is additional content added to the File.


Conclusion :

In this Kotlin Tutorial – Append text to file, we have learnt to use File.apendText() to append text to a file with the help of an example.