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
🌐
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.
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 &gt; 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
🌐
BezKoder
bezkoder.com › home › ways to write to file in kotlin
Ways to write to File in Kotlin - BezKoder
January 24, 2024 - With PrintWriter, we can use println() function so that it’s helpful to write line by line. File(name).printWriter().use { out -> out.println(line1) out.println(line2) } ... package com.bezkoder.kotlin.writefile import java.io.File fun main(args: ...
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io.path › java.nio.file.-path › write-lines.html
writeLines - Kotlin Programming Language
August 1, 2023 - ... fun Path.writeLines( lines: ... OpenOption ): Path (source) Write the specified collection of char sequences lines to a file terminating each one with the platform's line separator....
🌐
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 example, the writeText function writes the content to example.txt. If the file exists, its content is overwritten. This approach is ideal for small files and simple tasks. If you want to append text instead of overwriting, Kotlin provides the appendText method.
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io.path › write-lines.html
writeLines | Core API – Kotlin Programming Language
... @IgnorableReturnValueinline ... options: OpenOption): Path(source) Write the specified sequence of char sequences lines to a file terminating each one with the platform's line separator....
🌐
TutorialKart
tutorialkart.com › kotlin › write-content-to-file-in-kotlin
Write to File in Kotlin
March 22, 2023 - Append the string to the file using PrintWriter.append() function. Close the writer. ... import java.io.PrintWriter /** * Example to use standard Java method in Kotlin to write content to a text file */ fun main(args: Array<String>) { // content ...
Find elsewhere
🌐
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!
🌐
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.
🌐
Programiz
programiz.com › kotlin-programming › examples › append-text-existing-file
Kotlin Program to Append Text to an Existing File
import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardOpenOption fun main(args: Array<String>) { val path = System.getProperty("user.dir") + "\\src\\test.txt" val text = "Added text" try { Files.write(Paths.get(path), text.toByteArray(), StandardOpenOption.APPEND) } catch (e: IOException) { } } When you run the program, the test.txt file now contains: ... In the above program, we use System's user.dir property to get the current directory stored in the variable path. Check Kotlin Program to get the current directory for more information.
🌐
Educative
educative.io › answers › how-to-write-to-a-file-in-kotlin
How to write to a file in Kotlin
text: We use this parameter text/string to write to a file. ... The writeBytes() method writes a ByteArray to the specified file.
🌐
Chercher
chercher.tech › null › null › read and write files in kotlin
Read and write files in Kotlin
August 29, 2018 - Chercher tech provides the tutorials for the future technologies, We are writing an article one per day Actually the author is not a developer, he is a tester first author thought to write a tutorial only for selenium then he thought for protractor python and then UI path now writing kotlin file operations · bufferedReader() to read contents of a file into BufferedReader · import java.io.File fun main(args: Array) { val file = File("chercher tech.txt") val bufferedReader = file.bufferedReader() val text:List = bufferedReader.readLines() for(line in text){ println(line) } } forEachLine() reads this file line by line using the specified charset and calls the action for each line.
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io › java.io.-file › write-text.html
writeText - Kotlin Programming Language
March 21, 2022 - kotlin-stdlib / kotlin.io / java.io.File / writeText · JVM · 1.0 · 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. text - text to write into file.
🌐
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. There could be scenarios where you may need to add a debug line to the report, or some log file, etc.
🌐
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
When executed, this sequence of operations will create a file named output.txt (if it doesn't exist), write the specified lines of text into it, and overwrite the content if the file already exists. The content of the file after executing Files.write will look like this: ... 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.
🌐
Kotlin
kotlinlang.org › docs › tutorials › kotlin-for-py › file-io.html
File I/O - Kotlin Programming Language
You can write binary data to a file by calling outputStream() on a file object and use the resulting OutputStream to write bytes.
🌐
Kotlin
kotlinandroid.org › kotlin android home › kotlin tutorials › kotlin file operations › kotlin – write string to text file
Kotlin – Write String to Text File
In the following example program, ... desired file path val file = File(filePath) val textToWrite = "Hello, Kotlin!" file.writeText(textToWrite) println("Text written to file successfully.") }...
🌐
Kotlin
kotlinandroid.org › kotlin android home › kotlin tutorials › kotlin file operations › kotlin – write list of strings as lines in a file
Kotlin – Write List of Strings as Lines in a File
To write a list of strings to a text file in Kotlin, follow these steps: Import the File class from the java.io package. Create a File object with the desired file path and name. Use printWriter() method to write each string in the list to a new line in the file.