🌐
TutorialKart
tutorialkart.com › kotlin › kotlin-create-file
Kotlin - Create File - Examples
March 22, 2023 - In this example, we will use File.writeBytes() to create a new File. ... import java.io.File fun main(args: Array<String>) { val fileName = "data.txt" var file = File(fileName) // create a new file file.writeBytes(ByteArray(0)) } We have given ...
🌐
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 - If we’d like to use a Java PrintWriter, Kotlin provides a printWriter function exactly for this purpose. With it, we can print formatted representations of objects to an OutputStream: ... This method returns a new PrintWriter instance. Next, we can take advantage of the method use to handle it: File(fileName).printWriter().use { out -> out.println(fileContent) }
🌐
Baeldung
baeldung.com › home › kotlin › kotlin io › reading from a file in kotlin
Reading from a File in Kotlin | Baeldung on Kotlin
April 28, 2026 - Calls a given block callback, giving it a sequence of all the lines in a file.
🌐
ZetCode
zetcode.com › kotlin › writefile
Kotlin write file - learn how to write a file in Kotlin
January 29, 2024 - The example writes two lines to a file with BufferedWriter. ... 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 ...
🌐
Android Developers
developer.android.com › api reference › file
File | 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 › latest › jvm › stdlib › kotlin.io › java.io.-file
java.io.File - Kotlin Programming Language
April 14, 2023 - The Kotlin Standard Library provides ... with Kotlin. These include: Higher-order functions implementing idiomatic patterns (let, apply, use, synchronized, etc). Extension functions providing querying operations for collections (eager) and sequences (lazy). Various utilities for working with strings and char sequences. Extensions for JDK classes making it convenient to work with files, IO, and ...
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
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.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 › 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 › docs › tutorials › kotlin-for-py › file-io.html
File I/O - Kotlin Programming Language
Kotlin has inherited Java's fidgety (but very flexible) way of doing I/O, but with some simplifying extra features. We won't get into all of it here, so for starters, this is how to iterate through all the lines of a file (you'll need import java.io.File):
Find elsewhere
🌐
Chercher
chercher.tech › null › null › read and write files in kotlin
Read and write files in Kotlin
August 29, 2018 - We will learn about how to use these filewriting methods in kotlin. File.createNewFile() creates a new file if it does not exist already and returns a Boolean value of true. If the file exists at the path provided, then createNewFile() functions returns false. The file created is empty and has zero bytes written to it. createNewFile() is the way in which the existing file will not be overridden. Remaining ways will overwrite the file if it exists. In the below example, we will try to create a new file and then we try to override it.
🌐
ZetCode
zetcode.com › kotlin › readfile
Kotlin read file - reading file in Kotlin
January 29, 2024 - In the examples, we use this text file. File.readLines reads the file content as a list of lines.
🌐
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.
🌐
FileFormat.com
docs.fileformat.com › programming › kt
KT File Format
May 20, 2021 - // The example code prints Hello World from Kotlin to the console.
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io
kotlin.io | Core API – Kotlin Programming Language
Reads the file content as a list of lines. ... Reads a line of input from the standard input stream and returns it, or throws a RuntimeException if EOF has already been reached when readln is called. ... This function is not supported in Kotlin/JS and throws UnsupportedOperationException.
🌐
Compile N Run
compilenrun.com › kotlin tutorial › kotlin io › kotlin file operations
Kotlin File Operations | Compile N Run
Let's look at some practical applications of file operations in Kotlin. This example reads a log file, filters specific entries, and exports them to a new file:
🌐
Hyperskill
hyperskill.org › learn › step › 6351
Reading files · Hyperskill
May 22, 2023 - We can also check the existence of a file with exists() method, which will return false in case of a missing file and true if Kotlin found it. Actually, you can use any method from File, for example, length() or delete().
🌐
DhiWise
dhiwise.com › post › simplifying-kotlin-read-from-file-a-practical-approach
Kotlin Read From File: Step-by-Step Instructions Simplified
January 21, 2025 - This blog will take you through the most common techniques to read files in Kotlin, showcasing practical examples and explaining concepts like file line-by-line reading, managing input streams, and dealing with file content.
🌐
Studytonight
studytonight.com › kotlin › kotlin-file-handling
Kotlin File Handling - Studytonight
This tutorial covers File handling in Kotlin. We will learn how to Read file, write and create file using readText(), writeText() ad createFile() functions.
🌐
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
In this lesson, we've covered the fundamental skills necessary for writing and appending text to files using Kotlin's Files class. You have learned how to use Files.write to write data and append new content to existing files using StandardOpenOption.APPEND.