File.appendText() – Append Text to File in Kotlin

To append text to a file in Kotlin, we can use File.appendText() method.

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.

Syntax

The syntax of File.appendText() method is

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

Usage

File(filename).appendText(textToBeAppended, charset)

where

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

Examples

1. Append Text to File

Following is the content of the original file.

file.txt

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

In the following program, we append a string in content variable to the existing file file.txt.

Main.kt

import java.io.File

fun main(args: Array) {
    val content= " This is additional content added to the File."
    File("file.txt").appendText(content)
}

Following is the content of file after appending string.

file.txt

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

Conclusion

In this Kotlin Tutorial, we learned how to append text to a file using File.appendText() method, with the help of examples.