The only difference is that creating a file creates a file with no classes, and creating a class creates a file with one class. You can then add more classes to the file, or delete classes, or make any other changes - the end result doesn't depend on how the file was created.

Answer from yole on Stack Overflow
🌐
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 - In this article, we saw the various ways of reading a file in Kotlin. Depending on the use case, we can either opt for reading the file line-by-line or reading it entirely as a 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 · 中文 – 简体
🌐
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) }
🌐
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 ...
🌐
OneUptime
oneuptime.com › home › blog › kotlin file io
Kotlin File IO
February 2, 2026 - The File class gains numerous Kotlin-specific extensions that eliminate boilerplate code while ensuring resources are properly closed.
🌐
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
🌐
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 - File handling in Kotlin is made easy thanks to the seamless integration with Java’s IO libraries. Whether you’re logging user data, reading config files, or creating logs, Kotlin gives you simple and readable ways to manage files.
🌐
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 · 中文 – 简体
🌐
Medium
medium.com › @sujitpanda › file-read-write-with-kotlin-io-31eff564dfe3
File Read/Write with Kotlin IO. In this post i will be explaining how… | by Sujit Panda | Medium
February 13, 2024 - I was working on an Android project that was written in Java. I was trying to port one Java file to Kotlin which had file read/write implementation in one method. So the first thing I did was just copy/paste that piece of Java code to my Kotlin file and it auto-converted that to Kotlin.
🌐
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.
🌐
FileFormat.com
docs.fileformat.com › programming › kt
KT File Format
May 20, 2021 - A source code written in Kotlin is saved with .kt extension which is commonly known as Kotlin file extension. The Kotlin is a general-purpose cross-platform programming language developed by JetBrains to be fully interoperable with Java.
🌐
TutorialKart
tutorialkart.com › kotlin › kotlin-create-file
Kotlin - Create File - Examples
March 22, 2023 - Kotlin Create File – In Kotlin, new file could be created using File.createNewFile(), File.writeText(text :String), Files.writeBytes() etc. There are many other ways to create a file in Kotlin.
🌐
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.
🌐
Medium
kabi20.medium.com › kotlin-file-handling-everything-you-need-to-know-896568dc769f
Kotlin File Handling: Everything You Need to Know - Kabi
May 9, 2026 - In the world of software development ... system is a fundamental skill. In Kotlin, the File class serves as our primary gateway to managing digital data stored on persistent storage....
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › org.w3c.files › -file
File - Kotlin Programming Language
June 15, 2021 - kotlin-stdlib / org.w3c.files / File · JS · 1.1 · open class File : Blob (source) Exposes the JavaScript File to Kotlin · JS · 1.1 · Exposes the JavaScript File to Kotlin · File( fileBits: Array<dynamic>, fileName: String, options: FilePropertyBag = definedExternally) JS ·
🌐
Medium
medium.com › @gok_diyar › file-operations-in-kotlin-617978d84204
FILE OPERATIONS IN KOTLIN. File handling process of Kotlin relies… | by Gokhan Diyaroglu | Medium
June 8, 2022 - FILE OPERATIONS IN KOTLIN File handling process of Kotlin relies on java.io.File and also kotlin.io package which comes in default. import java.io.File var dataDir = File(“.”) //get the root …
🌐
FileSuffix
filesuffix.com › browser › development files › kotlin file
KOTLIN file - What is it and how to open it?
September 26, 2025 - Description: The KOTLIN file belongs to the KT format family. The KT format serves as Kotlin Source Code linked to the Development category. This file type is widely used to store data required by Kotlin.
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)
}