A bit more idiomatic. For PrintWriter, this example:

File("somefile.txt").printWriter().use { out ->
    history.forEach {
        out.println("{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.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.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

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.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.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.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
40

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.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.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.value}" }

history.entries.toFile("somefile.txt") {  "{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.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)
}
🌐
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 - Kotlin provides various ways of writing into a file in the form of extension methods for java.io.File. We’ll use several of these to demonstrate different ways in which we can achieve this using Kotlin: writeText – lets us write directly from a String
Discussions

KMM: Write file to directory
Check out okio https://square.github.io/okio/multiplatform/ More on reddit.com
🌐 r/Kotlin
9
6
January 17, 2024
How to write data to file in Kotlin - Stack Overflow
A little while ago, I started learning Kotlin, and I have done its basics, variables, classes, lists, and arrays, etc. but the book I was learning from seemed to miss one important aspect, reading ... More on stackoverflow.com
🌐 stackoverflow.com
How to read and write txt files in android in kotlin - Stack Overflow
I'm still pretty much a beginner in kotlin and android studio. I can access most of the android widgets but I cannot access files and so far I managed to come across only the following code which d... More on stackoverflow.com
🌐 stackoverflow.com
November 21, 2018
How to read and write files to my Android device? - Android - Kotlin Discussions
In the app that I am creating I would like to write some text to a file and store it on the device where I can later access that file through the file explorer on the device. Is there a way to do this? I tried implementing this using a fileOutputStream but it seems that this writes the file ... More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
0
February 12, 2022
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io › write-text.html
writeText | Core API – Kotlin Programming Language
kotlin-stdlib/kotlin.io/writeText · JVM · fun File.writeText(text: String, charset: Charset = Charsets.UTF_8)(source) Sets the content of this file as text encoded using UTF-8 or specified charset. If this file exists, it becomes overwritten. 1.0 · text · text to write into file.
🌐
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
Specify the Output File Path: Start by defining the file path where your data will be stored. In Kotlin, this is done using the Paths.get() function to create a Path object. Write Data to the File: Use the Files.write method to write the desired content to the file.
🌐
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 - fun writeToFile(context: Context, fileName: String, data: String) { try { context.openFileOutput(fileName, Context.MODE_PRIVATE).use { it.write(data.toByteArray()) } Log.d("FileExample", "Data written successfully!") } catch (e: Exception) { e.printStackTrace() } }
🌐
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 · 中文 – 简体
Find elsewhere
🌐
Medium
medium.com › @YodgorbekKomilo › day-18-file-handling-in-kotlin-reading-writing-files-made-simple-da774d449459
📁 Day 18 — File Handling in Kotlin: Reading & Writing Files Made Simple! | by Yodgorbek Komilov | Medium
May 5, 2025 - Let’s explore how to work with files using Kotlin’s standard library and Java IO integration. Kotlin doesn’t have its own file system APIs but leverages Java’s. Here’s how you can write text to a file:
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io › write-bytes.html
writeBytes | Core API – Kotlin Programming Language
kotlin-stdlib/kotlin.io/writeBytes · JVM · fun File.writeBytes(array: ByteArray)(source) Sets the content of this file as an array of bytes. If this file already exists, it becomes overwritten. 1.0 · array · byte array to write into this file. Thanks for your feedback!
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io.path › write-lines.html
writeLines | Core API – Kotlin Programming Language
kotlin-stdlib/kotlin.io.path/writeLines ... OpenOption): Path(source) Write the specified collection of char sequences lines to a file terminating each one with the platform's line separator....
🌐
YouTube
youtube.com › watch
Kotlin How to Write to Text File - YouTube
Learn How to Write to Text File in Kotlin. Learn How to Write to Text File with example in Kotlin.
Published   November 8, 2019
Views   2K
🌐
YouTube
youtube.com › watch
Working With Files In Kotlin - IO Essentials - YouTube
In this video you'll learn about files in JVM based environments, specifically about referencing files and folders in our code, file permissions and traversi...
Published   January 19, 2025
🌐
Android Developers
developer.android.com › api reference › files
Files | 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 · 中文 – 简体
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io › writer.html
writer | Core API – Kotlin Programming Language
kotlin-stdlib/kotlin.io/writer · JVM · inline fun File.writer(charset: Charset = Charsets.UTF_8): OutputStreamWriter(source) Returns a new FileWriter for writing the content of this file. 1.0 · inline fun OutputStream.writer(charset: Charset = Charsets.UTF_8): OutputStreamWriter(source) Creates a writer on this output stream using UTF-8 or the specified charset.
🌐
Hyperskill
hyperskill.org › learn › step › 9710
Writing files
Hyperskill is an educational platform for learning programming and software development through project-based courses, that helps you secure a job in tech. Master Python, Java, Kotlin, and more with real-world coding challenges.
🌐
Kotlin Discussions
discuss.kotlinlang.org › android
How to read and write files to my Android device? - Android - Kotlin Discussions
February 12, 2022 - In the app that I am creating I would like to write some text to a file and store it on the device where I can later access that file through the file explorer on the device. Is there a way to do this? I tried implementing this using a fileOutputStream but it seems that this writes the file ...
🌐
Kotlin
kotlinandroid.org › kotlin android home › kotlin tutorials › kotlin file operations › kotlin – write string to text file
Kotlin – Write String to Text File
Create a File object with the desired file path and name. Use the writeText() method to write a string to the file.
🌐
Kotlin-quick-reference
kotlin-quick-reference.com › 050-R-input-output-io.html
I/O · Kotlin Quick Reference
That approach default to the UTF-8 character set. You can also specify the Charset when using writeText: File(filename).writeText(string, Charset.forName("UTF-16"))