Both File.bufferedWriter and File.printWriter actually rewrite the target file, replacing its content with what you write with them. This is mostly equivalent to what would happen if you used f.writeText(...), not f.appendText(...).

One solution would be to create a FileOutputStream in the append mode by using the appropriate constructor FileOutputStream(file: File, append: Boolean), for example:

FileOutputStream(f, true).bufferedWriter().use { writer ->
    //... 
}
Answer from hotkey on Stack Overflow
🌐
Baeldung
baeldung.com › home › kotlin › kotlin io › writing to a file in kotlin
Writing to a File in Kotlin | Baeldung on Kotlin
April 28, 2026 - Similar to writeText() and writeBytes(), the appendText() and appendBytes() functions are also File extensions. As their names imply, these two extensions append new content to the file instead of overwriting the original file: File(fileName).appendText(newContent) File(fileName).appendBytes(newContentAsArray) In this article, we explored different ways of writing and appending a file using Kotlin’s File extensions.
🌐
Kotlin Discussions
discuss.kotlinlang.org › support
Appending to a text file with FileWriter & bufferedWriter - Support - Kotlin Discussions
March 16, 2022 - Hi All, In the following example using FileWriter, two lines are appended to a text file using both the .write() and .append() methods, when the context mode is set to APPEND (true)… File("test_file2.txt").bufferedWriter().use { out-> out.write(("Line 1\r\n")) out.write(("Line 2\r\n")) } FileWriter( "test_file2.txt", true ).use { out -> out.write("Appended Line 3\r\n") // append works here out.append("Appended Line 4\r\n") // append works here too!
People also ask

How to write to a file in Kotlin Android?
To write to a file in Kotlin for Android, use the File class and its writeText or appendText methods. For example, save data to a file within the app's internal storage: ```kotlin import java.io.File val file = File(context.filesDir, "example.txt") file.writeText("Hello, Kotlin Android!") ``` When writing to external storage on Android, ensure you have the necessary permissions (WRITE\_EXTERNAL\_STORAGE for older versions or MANAGE\_EXTERNAL\_STORAGE for scoped storage). Always check and request permissions at runtime.
🌐
dhiwise.com
dhiwise.com › post › how-to-use-kotlin-write-to-file-practical-methods
Kotlin Write to File: A Complete Guide For File Handling
How to make a Kotlin file?
To create a Kotlin file in your IDE (e.g., IntelliJ or Android Studio), right-click a directory in your project, select `**New > Kotlin File/Class**`, and specify the filename. For programmatic file creation, use: ```kotlin import java.io.File val file = File("newfile.txt") file.createNewFile() ``` This creates the file at the specified path.
🌐
dhiwise.com
dhiwise.com › post › how-to-use-kotlin-write-to-file-practical-methods
Kotlin Write to File: A Complete Guide For File Handling
How to convert string to file in Kotlin?
You can convert a String to a file by writing its content using the writeText method. For example: ```kotlin import java.io.File val content = "This is my string" val file = File("example.txt") file.writeText(content) ``` This saves the string as a text file. Adjust the file path as needed.
🌐
dhiwise.com
dhiwise.com › post › how-to-use-kotlin-write-to-file-practical-methods
Kotlin Write to File: A Complete Guide For File Handling
🌐
CodeSignal
codesignal.com › learn › courses › fundamentals-of-text-data-manipulation-in-kotlin › lessons › writing-to-files-in-kotlin
Writing to Files in Kotlin | CodeSignal Learn
Sometimes, you may want to add data to an existing file without overwriting its current contents. This can be easily achieved in Kotlin using the Files.write method with the StandardOpenOption.APPEND flag.
🌐
Programiz
programiz.com › kotlin-programming › examples › append-text-existing-file
Kotlin Program to Append Text to an Existing File
In the above program, we use System's ... Likewise, the text to be added is stored in the variable text. Then, inside a try-catch block we use Files' write() method to append text to the existing file....
🌐
BezKoder
bezkoder.com › home › ways to write to file in kotlin
Ways to write to File in Kotlin - BezKoder
January 24, 2024 - To append text to existing file, use appendText(). val myFile = File(name) myFile.writeText(text) myFile.appendText(nextText) ... package com.bezkoder.kotlin.writefile import java.io.File fun main(args: Array<String>) { val outStr1: String = ...
🌐
Techie Delight
techiedelight.com › home › java › add text to end of a file in kotlin
Add text to end of a file in Kotlin | Techie Delight
2 weeks ago - There are numerous methods to add text at the end of a file in Kotlin: 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 ...
🌐
TutorialKart
tutorialkart.com › kotlin › append-text-to-file-in-kotlin
How to append text to file in Kotlin?
March 22, 2023 - To append text to a file in Kotlin, we can use File.appendText() method.
Find elsewhere
🌐
Medium
cdpateldigitalroom.medium.com › files-in-android-read-write-append-data-using-kotlin-7a6b2d70de1c
📂 Files in Android: Read, Write & Append Data using Kotlin 📖 | by Sarthak Education (CDPatel Digital Room) | Medium
April 26, 2025 - Sometimes, we don’t want to erase old data — we just want to add more text to the end 📌 · fun appendToFile(context: Context, fileName: String, data: String) { try { context.openFileOutput(fileName, Context.MODE_APPEND).use { it.write(("\n$data").toByteArray()) } Log.d("FileExample", "Data appended successfully!") } catch (e: Exception) { e.printStackTrace() } }
🌐
DhiWise
dhiwise.com › post › how-to-use-kotlin-write-to-file-practical-methods
Kotlin Write to File: A Complete Guide For File Handling
January 21, 2025 - In this blog, we’ll walk you through how Kotlin write-to-file works with clear examples and tips. 📝 · Kotlin simplifies file handling by leveraging its expressive syntax and Java compatibility. Writing to files involves saving text to a txt file, appending data, or working with structured ...
🌐
Chercher
chercher.tech › null › null › read and write files in kotlin
Read and write files in Kotlin
August 29, 2018 - One of the common examples of appending text to file is logging · import java.io.File fun main(args: Array) { val filename = "chercher tech.txt" // content to be written to file var content:String = "dummy text to show writing to file in kotlin chercher tech" // write content to file File(filename).writeText(content) File(filename).appendText("ppppppp") } Excel Files with apache poi ·
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io › java.io.-file › append-text.html
appendText - Kotlin Programming Language
June 17, 2022 - Try the revamped Kotlin docs design! ... Appends text to the content of this file using UTF-8 or the specified charset.
Top answer
1 of 8
131

A bit more idiomatic. For PrintWriter, this example:

File("somefile.txt").printWriter().use { out ->
    history.forEach {
        out.println("${it.key}, ${it.value}")
    }
}

The for loop, or forEach depends on your style. No reason to use append(x) since that is basically write(x.toString()) and you already give it a string. And println(x) basically does write(x) after converting a null to "null". And println() does the correct line ending.

If you are using data classes of Kotlin, they can already be output because they have a nice toString() method already.

Also, in this case if you wanted to use BufferedWriter it would produce the same results:

File("somefile.txt").bufferedWriter().use { out ->
    history.forEach {
        out.write("${it.key}, ${it.value}\n")
    }
}

Also you can use out.newLine() instead of \n if you want it to be correct for the current operating system in which it is running. And if you were doing that all the time, you would likely create an extension function:

fun BufferedWriter.writeLn(line: String) {
    this.write(line)
    this.newLine()
}

And then use that instead:

File("somefile.txt").bufferedWriter().use { out ->
    history.forEach {
        out.writeLn("${it.key}, ${it.value}")
    }
}

And that's how Kotlin rolls. Change things in API's to make them how you want them to be.

Wildly different flavours for this are in another answer: https://stackoverflow.com/a/35462184/3679676

2 of 8
39

Other fun variations so you can see the power of Kotlin:

A quick version by creating the string to write all at once:

File("somefile.txt").writeText(history.entries.joinToString("\n") { "${it.key}, ${it.value}" })
// or just use the toString() method without transform:
File("somefile.txt").writeText(x.entries.joinToString("\n"))

Or assuming you might do other functional things like filter lines or take only the first 100, etc. You could go this route:

File("somefile.txt").printWriter().use { out ->
    history.map { "${it.key}, ${it.value}" }
           .filter { ... }
           .take(100)
           .forEach { out.println(it) }
}

Or given an Iterable, allow writing it to a file using a transform to a string, by creating extension functions (similar to writeText() version above, but streams the content instead of materializing a big string first):

fun <T: Any> Iterable<T>.toFile(output: File, transform: (T)->String = {it.toString()}) {
    output.bufferedWriter().use { out ->
        this.map(transform).forEach { out.write(it); out.newLine() }
    }
}

fun <T: Any> Iterable<T>.toFile(outputFilename: String, transform: (T)->String = {it.toString()}) {
    this.toFile(File(outputFilename), transform)
}

used as any of these:

history.entries.toFile(File("somefile.txt")) {  "${it.key}, ${it.value}" }

history.entries.toFile("somefile.txt") {  "${it.key}, ${it.value}" }

or use default toString() on each item:

history.entries.toFile(File("somefile.txt")) 

history.entries.toFile("somefile.txt") 

Or given a File, allow filling it from an Iterable, by creating this extension function:

fun <T: Any> File.fillWith(things: Iterable<T>, transform: (T)->String = {it.toString()}) {
    this.bufferedWriter().use { out ->
        things.map(transform).forEach { out.write(it); out.newLine() }
    }
}

with usage of:

File("somefile.txt").fillWith(history.entries) { "${it.key}, ${it.value}" }

or use default toString() on each item:

File("somefile.txt").fillWith(history.entries) 

which if you had the other toFile extension already, you could rewrite having one extension call the other:

fun <T: Any> File.fillWith(things: Iterable<T>, transform: (T)->String = {it.toString()}) {
    things.toFile(this, transform)
}
🌐
Android Developers
developer.android.com › api reference › filewriter
FileWriter | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Beecoder
beecoder.org › english › kotlin › append text to an existing file
Append Text to an Existing File, Kotlin | 🐝 / Coder
July 23, 2025 - Kotlin - Convert Milliseconds to Minutes and Seconds · #append #file #kotlin #text · Append text to existing file · Kotlin · Output result · This is a Test file.Added text · Append text to an existing file using FileWriter · Kotlin · code examples and answer to questions in Kotlin programming luaguage ·
🌐
Kotlin Discussions
discuss.kotlinlang.org › support
Appending to a text file with FileWriter & bufferedWriter - #5 by Slouch - Support - Kotlin Discussions
March 17, 2022 - Hi All, In the following example using FileWriter, two lines are appended to a text file using both the .write() and .append() methods, when the context mode is set to APPEND (true)… File("test_file2.txt").bufferedWri…
🌐
ZetCode
zetcode.com › kotlin › writefile
Kotlin write file - learn how to write a file in Kotlin
January 29, 2024 - The bufferedWriter returns a BufferedWriter for writing the content to the file. The use method executes the given block function on the file and then closes it. The writeText is a Kotlin File extension function which writes text encoded using UTF-8 or other charset to the file.
🌐
TutorialKart
tutorialkart.com › kotlin › write-content-to-file-in-kotlin
Write to File in Kotlin
March 22, 2023 - ... In this example, we take a ... as a string in a variable. Initialize a PrintWriter object. Append the string to the file using PrintWriter.append() function....
🌐
Gyata
gyata.ai › kotlin › kotlin-write-to-file
Kotlin Write To File | Gyata - Learn about AI, Education & Technology
December 9, 2023 - If you want to add to the existing content instead of replacing it, use the `appendText()` or `appendBytes()` methods. Ensure that the file is not being used by another process. If it is, you'll get an IOException. This is a common error especially when dealing with system files or files being ...