You can use the writeBytes function:

fun File.writeBytes(array: ByteArray)
Answer from André Jesus 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 - The method writeBytes takes a ByteArray as an argument and directly writes it into the specified file. This is useful when we have the contents as an array of bytes rather than plain text.
🌐
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.
Discussions

java - Convert large bytesarray to file in kotlin - Stack Overflow
hi i have a large bytesarray and i want to convert to file in sdcard i used this code but crash sometimes what is the best way to convert bytesarray to file in kotlin? private fun More on stackoverflow.com
🌐 stackoverflow.com
android - Converting a byte array to a pdf file then saving it - Stack Overflow
I'm hitting an API Endpoint with a Kotlin Android app. In this API call I'm returning a byte Array. What I would like to see is a way to convert the byte array to a pdf file and save it in the ph... More on stackoverflow.com
🌐 stackoverflow.com
About write a UByteArray to the file - Libraries - Kotlin Discussions
Is there any way to write a UbyteArray to the file directly? More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
0
January 8, 2019
How do I write to a file in Kotlin? - Stack Overflow
I can't seem to find this question yet, but what is the simplest, most-idiomatic way of opening/creating a file, writing to it, and then closing it? Looking at the kotlin.io reference and the Java More on stackoverflow.com
🌐 stackoverflow.com
February 18, 2016
🌐
Reddit
reddit.com › r/kotlin › how to efficiently write bytes to file with buffer?
r/Kotlin on Reddit: How to efficiently write bytes to file with buffer?
July 18, 2021 -

I am making my first evolutionary sim while also learning Kotlin. I want to save the state of epochs (what happens in each simulation) and am making a binary encoding to help with efficiency. I want to write bytes to a file in a buffered fashion (write every 10kb or something).

I am trying to attack this by writing a ByteArray and tracking the number of bytes "added", and then writing and resetting when it hits the limit. This would require a conditional statement for every byte I write to the buffer though, I was wondering if this is naive?

Thanks in advance for any help!

🌐
ZetCode
zetcode.com › kotlin › writefile
Kotlin write file - learn how to write a file in Kotlin
January 29, 2024 - The example writes to a file with Kotlin writeText extension function. The Files.write writes bytes to a file.
🌐
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.io › java.io.-file › write-bytes.html
writeBytes - Kotlin Programming Language
August 18, 2022 - Try the revamped Kotlin docs design! ... Sets the content of this file as an array of bytes.
🌐
CodeVsColor
codevscolor.com › different ways to write to a file in kotlin - codevscolor
Different ways to write to a file in Kotlin - CodeVsColor
February 4, 2021 - Below program shows how we can ...nStr.toByteArray()) } Here, we are converting the string givenStr to a byte array using toByteArray() method and writing that in the file using writeBytes ·...
🌐
BezKoder
bezkoder.com › home › ways to write to file in kotlin
Ways to write to File in Kotlin - BezKoder
January 24, 2024 - Kotlin also provides appendBytes() function to append array of bytes to the content of existing file. val myFile = File(name) myFile.writeBytes(bytesArray) myFile.appendBytes(nextBytesArray) For example: package com.bezkoder.kotlin.writefile ...
Find elsewhere
🌐
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.
🌐
Medium
medium.com › @vahidnety › save-bytearray-data-into-a-file-in-android-kotlin-a297c6800184
Save bytearray data into a file in android Kotlin | by Vahid D | Medium
May 1, 2023 - To save a ByteArray to a file in Kotlin on Android, you can use the FileOutputStream class along with the write() method.
🌐
TutorialKart
tutorialkart.com › kotlin › kotlin-create-file
Kotlin - Create File - Examples
March 22, 2023 - You may provide the string you would like to write into this file. File.writeBytes() creates a new file if it does not exist already and writes the raw bytes of the ByteArray provided to the file created.
🌐
Kotlin
kotlinlang.org › docs › tutorials › kotlin-for-py › file-io.html
File I/O - Kotlin Programming Language
val stream = File("data.txt").inputStream() val bytes = ByteArray(16) stream.read(bytes) stream.close() println(bytes) It's important to close a stream when you're done with it; otherwise, your program will leak a file handle. See the next section for how do do this nicely. If you've got one string that you want to write to a file, overwriting the existing contents if the file already exists, do this (again, UTF-8 is the default encoding):
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)
}
🌐
Baeldung
baeldung.com › home › kotlin › kotlin io › writing inputstream to file in kotlin
Writing InputStream to File in Kotlin | Baeldung on Kotlin
April 28, 2026 - However, we’ll only cover the most idiomatic approaches in the standard libraries here, as they’re pretty mature nowadays. One simple solution is to first read all the bytes from the InputStream and then write it to the file:
🌐
GitHub
github.com › JetBrains › kotlin › blob › master › libraries › stdlib › jvm › src › kotlin › io › FileReadWrite.kt
kotlin/libraries/stdlib/jvm/src/kotlin/io/FileReadWrite.kt at master · JetBrains/kotlin
this.write(byteBuffer.array(), 0, byteBuffer.position()) ... public fun File.forEachBlock(action: (buffer: ByteArray, bytesRead: Int) -> Unit): Unit = forEachBlock(DEFAULT_BLOCK_SIZE, action)
Author   JetBrains
🌐
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.
🌐
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.
🌐
Sling Academy
slingacademy.com › article › working-with-binary-files-in-kotlin
Working with Binary Files in Kotlin - Sling Academy
November 30, 2024 - In this code snippet, we read each byte from the file located at filePath until we reach the end of the file, which is indicated by the method read() returning -1. To write data to a binary file, you can use FileOutputStream, which enables writing byte data to files efficiently.