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.
The important point is that appendText() adds the new text at the end of the existing file content. It does not remove the old content and it does not automatically insert a new line unless the text you pass contains \n or System.lineSeparator().
Kotlin File.appendText() Syntax
The syntax of File.appendText() method is
fun File.appendText(
?text: String,
?charset: Charset = Charsets.UTF_8)
In regular Kotlin notation, the function can be read as an extension function on java.io.File that accepts the text to append and an optional character set. The default character set is UTF-8.
fun File.appendText(text: String, charset: Charset = Charsets.UTF_8)
Usage
File(filename).appendText(textToBeAppended, charset)
where
| Parameter | Required / Optional | Description |
| filename | Required | Name of the text file to which textToBeAppended is appended. |
| textToBeAppended | Required | The string which is appended to the specified file. |
| charset | Optional | The default Charset used is Charsets.UTF_8. You may specify any other Charset if required. |
How File.appendText() Works in Kotlin
File.appendText() opens the target file in append mode and writes the supplied string using the selected character set. If the file already has content, the new string is written after the last character in the file. If the file does not exist, Kotlin can create it, provided the parent directory exists and the program has permission to write there.
appendText()is best suited for small text additions such as log lines, notes, reports, or simple text output.- It appends exactly the string you provide; add a newline yourself when each entry should start on a new line.
- It uses
Charsets.UTF_8by default, which is suitable for most text files. - It may throw an exception if the path is invalid, the parent directory is missing, or the file cannot be written.
Kotlin appendText() 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.
2. Append Text to a New Line in Kotlin File
When appending log entries or report lines, you usually want the new text to appear on a separate line. In that case, include a line separator before or after the text you append.
Main.kt
import java.io.File
fun main() {
val file = File("app-log.txt")
val logLine = "Application started"
file.appendText(System.lineSeparator() + logLine)
}
If the file already contains Previous log entry, the content after running the program will be similar to the following.
Previous log entry
Application started
You may also append the line separator at the end of each entry. This is often cleaner for log files because every appended record completes its own line.
import java.io.File
fun main() {
val file = File("app-log.txt")
file.appendText("Application started" + System.lineSeparator())
file.appendText("User logged in" + System.lineSeparator())
}
3. Append Text to File with UTF-8 Charset in Kotlin
The second parameter of appendText() lets you specify the character set. If you do not pass it, Kotlin uses Charsets.UTF_8. You can still pass it explicitly when you want the code to clearly show the encoding used for the file.
import java.io.File
fun main() {
val file = File("notes.txt")
val content = "Kotlin file append example\n"
file.appendText(content, Charsets.UTF_8)
}
Use the same charset consistently while writing and reading the file. Mixing encodings can result in unreadable characters, especially when the file contains non-English text or special symbols.
4. Append Multiple Lines to a Kotlin File
For multiple lines, build the text first and call appendText() once. This keeps the code simple and avoids repeated file opening for each small line.
import java.io.File
fun main() {
val file = File("report.txt")
val linesToAppend = listOf(
"Total users: 25",
"Active users: 18",
"Inactive users: 7"
).joinToString(separator = System.lineSeparator(), postfix = System.lineSeparator())
file.appendText(linesToAppend)
}
The joinToString() call creates one string with proper line separators. The postfix adds a final line break after the last line.
Append Text to File Safely with Exception Handling in Kotlin
File operations can fail. For example, the application may not have write permission, the path may be invalid, or the parent directory may not exist. Use try and catch when the file operation is part of a real application flow.
import java.io.File
import java.io.IOException
fun main() {
val file = File("logs/app-log.txt")
try {
file.parentFile?.mkdirs()
file.appendText("New log entry" + System.lineSeparator())
println("Text appended successfully.")
} catch (e: IOException) {
println("Could not append text to file: ${e.message}")
}
}
In this example, mkdirs() creates the parent directory if it is missing. The catch block handles input/output errors without abruptly stopping the program.
File.appendText() vs writeText() in Kotlin
Kotlin provides both appendText() and writeText() for text files, but they are used for different purposes.
| Kotlin file function | What it does | When to use |
|---|---|---|
appendText() | Adds text at the end of the existing file content. | Use it for logs, reports, notes, audit lines, and incremental text output. |
writeText() | Writes text to the file and replaces the existing content. | Use it when you want to create or overwrite the full file content. |
Use appendText() when preserving existing file content is required. Use writeText() only when overwriting the file is intended.
When to Use BufferedWriter Instead of appendText()
appendText() is convenient for small append operations. If you need to append many lines in a loop or write large amounts of text, a buffered writer is usually a better option because the file can stay open while multiple writes are performed.
import java.io.File
fun main() {
val file = File("numbers.txt")
file.bufferedWriter().use { writer ->
for (number in 1..5) {
writer.appendLine("Number: $number")
}
}
}
The use block closes the writer automatically after the writing is complete. This approach is helpful when the program writes many lines together.
Common Mistakes When Appending Text to a File in Kotlin
- Expecting a newline automatically:
appendText()does not add a newline by itself. Add\norSystem.lineSeparator()explicitly. - Using writeText() by mistake:
writeText()overwrites existing content, whileappendText()preserves it. - Ignoring the parent directory: Kotlin can create a missing file, but not a missing parent folder unless you create it first.
- Hardcoding platform-specific paths: Prefer safe path construction instead of writing paths that work only on one operating system.
- Using appendText() inside a large loop: For many repeated writes, use
bufferedWriter()or another stream-based approach.
Kotlin Append Text to File FAQ
How to append text to file in Kotlin?
Use File("file.txt").appendText("text to append"). Import java.io.File before using it. This adds the given text to the end of the file without deleting the existing content.
Does Kotlin appendText() create the file if it does not exist?
Yes, the file can be created if it does not exist and the program has permission to write at that location. However, if the parent directory does not exist, create it first using mkdirs().
Does appendText() add a new line automatically in Kotlin?
No. appendText() appends exactly the text passed to it. To append on a new line, include System.lineSeparator() or \n in the string.
What is the default charset used by Kotlin appendText()?
The default charset is Charsets.UTF_8. You can pass another charset as the second argument if the file must be written using a different encoding.
Should I use appendText() for large files in Kotlin?
Use appendText() for small and simple append operations. For many lines or repeated writes, prefer bufferedWriter() or another stream-based method to avoid opening the file repeatedly.
Editorial QA Checklist for Kotlin File.appendText()
- Confirm that every new code block uses a PrismJS-compatible Kotlin or output class.
- Check that examples distinguish
appendText()fromwriteText()clearly. - Verify that newline behavior is explained with
System.lineSeparator()or\n. - Ensure file creation notes mention missing parent directories and write permission.
- Keep FAQ answers specific to appending text to files in Kotlin, not generic file handling.
Conclusion
In this Kotlin Tutorial, we learned how to append text to a file using File.appendText() method, with the help of examples.
TutorialKart.com