How to append text to file in Kotlin using File.appendText()

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 :

File(filename).appendText(textToBeAppended, charset)

where :

PARAMETERREQUIRED/
OPTIONAL
DESCRIPTION
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.

You may be also interested in reading content of file, or write content to file.