Check this post - https://www.baeldung.com/kotlin/csv-files - it contains a few nice references to some libraries or pure Kotlin approaches if you prefer to use those.

Applying it to your use case, maybe something like:

fun OutputStream.writeCsv(context: Context, listOfData: List<YourData>) {
    //get data create directory
   ......

    val writer = bufferedWriter()
    writer.write(""""Name", "Address", "Code"""")
    writer.newLine()
    listOfData.forEach {
        writer.write("${it.name}, ${it.address}, \"${it.code}\"")
        writer.newLine()
    }
    writer.flush()
    writer.close()
}

And then call this where you need it,

FileOutputStream("out777.cs").apply { writeCsv(listOfData) }

One thing to note here is using bufferedWriter:

FileWriter writes directly into Files and should be used only when the number of writes is less. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better.

Not tested but this might point you in a more cleaner and efficient solution. There are also some libraries specifically for this. Take a look

Answer from moondev on Stack Overflow
🌐
Baeldung
baeldung.com › home › kotlin › kotlin io › read and write csv files with kotlin
Read and Write CSV Files With Kotlin | Baeldung on Kotlin
March 19, 2024 - Thanks to the schema, the writer knows the number and the order of the columns. The advantage of the Jackson library is that we can parse CSV rows straight into the data class objects, which are easy to deal with. In this tutorial, we parsed and wrote CSV with various methods. We can use pure Kotlin ...
🌐
GitHub
github.com › jsoizo › kotlin-csv
GitHub - jsoizo/kotlin-csv: Pure Kotlin CSV Reader/Writer · GitHub
Pure Kotlin Multiplatform CSV reader and writer.
Starred by 747 users
Forked by 52 users
Languages   Kotlin
🌐
Medium
medium.com › att-israel › jackson-csv-reader-writer-using-kotlin-f37ae771bd6d
Jackson CSV Reader/Writer Using Kotlin | by Ittay Stern | AT&T Israel Tech Blog | Medium
September 16, 2020 - Jackson CSV Reader/Writer Using Kotlin So you’re writing in Kotlin and you want to load your CSV files to a List, or maybe dump your Collection to a CSV file. This is 100% reasonable, given that
🌐
ZetCode
zetcode.com › kotlin › csv
Kotlin CSV - read, write CSV files in Kotlin
January 29, 2024 - package com.zetcode import com.github.doyaaaaaken.kotlincsv.dsl.csvWriter fun main() { val rows = listOf(listOf(1, 2, 3), listOf(4, 5, 6)) val fileName = "src/main/resources/data.csv" csvWriter().open(fileName) { rows.forEach { row -> writeRow(row) } } } A list of lists is written to the data.csv file.
🌐
Stack Abuse
stackabuse.com › reading-and-writing-csv-files-in-kotlin-with-apache-commons
Reading and Writing CSV Files in Kotlin with Apache Commons
February 27, 2023 - In this tutorial, we'll go over how to read and write CSV files in Kotlin, using the Apache Commons library, with examples of reading and writing custom objects.
🌐
Gitbook
kenta-koyama-biz.gitbook.io › kotlin-csv
README | kotlin-csv
January 20, 2024 - val rows = listOf(listOf("a", "b", "c"), listOf("d", "e", "f")).asSequence() csvWriter().openAsync(testFileName) { delay(100) //other suspending task rows.asFlow().collect { delay(100) // other suspending task writeRow(it) } } ... val rows = listOf(listOf("a", "b", "c"), listOf("d", "e", "f")) val csvString: String = csvWriter().writeAllAsString(rows) //a,b,c\r\nd,e,f\r\n ... val row1 = listOf("a", "b", "c") @OptIn(KotlinCsvExperimental::class) val writer = csvWriter().openAndGetRawWriter("test.csv") writer.writeRow(row1) writer.close()
🌐
Floern
floern.com
CSV in Kotlin with Casting CSV – floern.com;;
Introduction and deep dive into Casting CSV, my open source Kotlin library to automagically read and write CSV with a one-liner using Kotlin data classes and reflection.
Find elsewhere
🌐
GitHub
github.com › retheviper › kotlin-seed
GitHub - retheviper/kotlin-seed: Kotlin CSV writer
Kotlin Data Class to CSV Converter Uses kotlin-csv by doyaaaaaken Inspired by Kotlin-Grass
Author   retheviper
Top answer
1 of 1
4

That tutorial on using Apache Commons for reading CSV is written with the assumption that you are writing for JVM, not Android. It's not simple to adapt it to Android. I don't think the Apache Commons library is necessary anyway, because CSV is such a simple text-based format.

Here are a couple of simple extension functions that can be called on a File to either read a CSV as a 2D List of Strings, or write a 2D List of Strings to a File. Think of the 2D list as a List of lines of data. Each value in the inner List is all the values in that line.

@Throws(IOException::class)
fun File.readAsCSV(): List<List<String>> {
    val splitLines = mutableListOf<List<String>>()
    forEachLine {
        splitLines += it.split(", ")
    }
    return splitLines
}

@Throws(IOException::class)
fun File.writeAsCSV(values: List<List<String>>) {
    val csv = values.joinToString("\n") { line -> line.joinToString(", ") }
    writeText(csv)
}

You should not do File IO operations on the main thread, because this freezes the UI and risks making your application crash with the Application Not Responding Error. It looks like you have some kind of game loop so I'm not sure how to apply this advice in your case.

Here are alternate versions of the above functions that use FileInputStream and FileOutputStream so they are more versatile on Android (since you can't get direct File access for some storage locations):

@Throws(IOException::class)
fun FileInputStream.readAsCSV() : List<List<String>> {
    val splitLines = mutableListOf<List<String>>()
    reader().buffered().forEachLine {
        splitLines += it.split(", ")
    }
    return splitLines
}

@Throws(IOException::class)
fun FileOutputStream.writeAsCSV(values: List<List<String>>) {
    val csv = values.joinToString("\n") { line -> line.joinToString(", ") }
    writer().buffered().use { it.write(csv) }
}
🌐
YouTube
youtube.com › anybody can program
Final Project, Part 2 (write a real CSV file with Kotlin!) - Learn How to Program for Beginners #7.2 - YouTube
Finish off your expense tracker from part 1! In the last video of the "Learn How to Program for Beginners" series we will learn to leverage the java standard...
Published   May 31, 2020
Views   1K
🌐
MojoAuth
mojoauth.com › parse-and-generate-formats › parse-and-generate-csv-with-kotlin
Parse and Generate CSV with Kotlin | Parse and Generate Formats
September 12, 2025 - Such libraries might not support modern CSV features or could harbor unaddressed bugs. Many libraries simplify header management. You can often configure them to automatically recognize and use the first row as headers, allowing you to access data by column name instead of index. import com.github.doyaaaaen.kotlin.csv.core.CsvReader val reader = CsvReader { header = true } val records = reader.read(File("data.csv")) records.forEach { row -> val name = row["Name"] println("Name: $name") }
🌐
DEV Community
dev.to › blackmo18 › kotlin-csv-kotlin-grass-2b8j
Kotlin CSV to Data Class Parser - DEV Community
December 31, 2021 - Update: The current version is 0.8.0 Features 1. Simple And... Tagged with kotlin, csv, parser.
🌐
The Code
javathecode.com › home › kotlin › mastering csv files in kotlin
Mastering CSV Files in Kotlin
October 9, 2024 - By leveraging libraries like the pure Kotlin CSV Reader/Writer and utilizing Kotlin's strengths, you can manipulate CSV data with precision and ease.
🌐
Kotlinlang
slack-chats.kotlinlang.org › t › 481890 › hi-all-i-just-released-an-csv-reader-writer-libray-rocket-th
Hi all I just released an csv reader writer libray rocket Th kotlinlang #feed
Hi, all. I just released an csv reader/writer libray! 🚀 (This is inspired by · scala-csv) And I’ll be very gratefull if you can give me feedback. Thank you. https://github.com/doyaaaaaken/kotlin-csv
🌐
GitHub
github.com › berlix › csv-kotlin
GitHub - berlix/csv-kotlin · GitHub
For most use cases, use writeCsv to write a Sequence or an Iterable of rows onto a File, Path, Writer, or OutputStream: val rows = listOf( listOf("firstName", "lastName"), listOf("Chew", "Bacca") ) File("data.csv").writeCsv(rows)
Author   berlix
🌐
GitHub
gist.github.com › ea035d29c90d24de6290b045796020a1
Example of usage of Kotlin builder to generate a CSV file representing bank transactions · GitHub
Example of usage of Kotlin builder to generate a CSV file representing bank transactions - TransactionBuilder.kt