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 - For our algorithm, however, it presents an extra challenge, as there are not only leading spaces but leading tabs. It also has a string field in the second column. Such a column would present a challenge for parsing with only Kotlin language tools. There are in fact pure Kotlin libraries for dealing with CSV, notably kotlin-csv.
🌐
ZetCode
zetcode.com › kotlin › csv
Kotlin CSV - read, write CSV files in Kotlin
January 29, 2024 - A list of lists is written to the data.csv file. ... In this article we have showed how to work with CSV in Kotlin.
🌐
GitHub
github.com › doyaaaaaken › kotlin-csv
GitHub - jsoizo/kotlin-csv: Pure Kotlin CSV Reader/Writer · GitHub
February 17, 2022 - For in-memory streams use reader.read(source) (commonMain kotlinx.io.Source) or reader.read(stream) (JVM java.io.InputStream). val rows = listOf( listOf("a", "b", "c"), listOf("d", "e", "f"), ) // To a String — eager val csv: String = writer.writeAll(rows) // To a File writer.writeToFile(rows, File("out.csv")) // Nullable writes emit null as an unquoted empty field.
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 - But instead of trying to convince you that this is going to be a rocky road, I want to show you how easy it is to build the whole robust solution with a dozen Kotlin lines, using FasterXML’s Jackson modules. Did you know that FasterXML has a small collection of data-formats libraries in addition to JSON? As a bonus, all of FasterXML’s great annotations will be in effect to guide our CSV serialization/deserialization rules. Eventually the usage will be simple and straight forward. For instance, if Item is your data-class and it matches the CSV file headers, we will read it using: val items: List<Item> = readCsvFile("$filesDir/data.csv")
🌐
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 - There's no need to use the printRecord() method for the header row itself, since we've already specified it with the withHeader() method of the CSVFormat. Without specifying the header there, we would've had to print out the first row manually. ... Don't forget to flush() and close() the printer ...
🌐
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.
🌐
Kotlin
kotlinlang.org › docs › data-analysis-work-with-data-sources.html
Retrieve data from files | Kotlin Documentation
3 weeks ago - Kotlin DataFrame library enables you to work with both non-structured and structured data. For data transformations, you can use such methods as .add(), .split(), .convert(), and .parse(). Additionally, this toolset enables the retrieval and manipulation of data from various structured file formats, including CSV, JSON, XLS, Parquet, and Apache Arrow.
Find elsewhere
🌐
DEV Community
dev.to › blackmo18 › kotlin-csv-kotlin-grass-2b8j
Kotlin CSV to Data Class Parser - DEV Community
December 31, 2021 - You get a list or sequence of object parsed into a data class. Also your PRs and feature requests are much appreciated if you had any issues. ... Cool, csv-parsing is a nice, self-contained but useful problem domain! I recently wrote a csv to Kotlin data class parser for my work at 'Which?' as well 😅. I called my project KSV.
🌐
Stack Overflow
stackoverflow.com › questions › 71296725 › kotlin-kotlinx-serialization-csv-multi-array-list
Kotlin kotlinx-serialization-csv multi array list - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... This is not a valid CSV file. I would be rather surprised if any standard CSV parser could parse it. ... val csv = """ Code, Values 1234, [[11111, 22222], [44444, 99999]] 1235, [[11], [21, 22], [31, 32, 33], [41, 42, 43, 44]] """ data class Item( val Code: Int, val Values: List<List<Int>> ) val result: List<Item> = csv .trimIndent() .lines() .drop(1) .map { line -> Item( line .substringBefore(",") .toInt(), line .substringAfter(",") .replace(" ", "") .removeSurrounding("[[", "]]") .split("],[") .map { group -> group .split(",") .map { value -> value.toInt() } } ) } result.forEach { println(it) } // Output: // Item(Code=1234, Values=[[11111, 22222], [44444, 99999]]) // Item(Code=1235, Values=[[11], [21, 22], [31, 32, 33], [41, 42, 43, 44]])
🌐
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
🌐
DataFrame Help
kotlin.github.io › dataframe › read.html
Read | DataFrame
May 27, 2026 - DataFrame.readCsv(URI("https://raw.githubusercontent.com/Kotlin/dataframe/master/data/jetbrains_repositories.csv").toURL()) Zip and GZip files are supported as well. ... val csv = """ A,B,C,D 12,tuv,0.12,true 41,xyz,3.6,not assigned 89,abc,7.1,false """.trimIndent() DataFrame.readCsvStr(csv) By default, CSV files are parsed using , as the delimiter. To specify a custom delimiter, use the delimiter argument: val df = DataFrame.readCsv( file, delimiter = '|', header = listOf("A", "B", "C", "D"), parserOptions = ParserOptions(nullStrings = setOf("not assigned")), )
🌐
Sling Academy
slingacademy.com › article › processing-csv-files-using-kotlins-file-api
Processing CSV Files Using Kotlin’s File API - Sling Academy
The joinToString() extension function converts an array or list into a string separated by specified characters, which is precisely what you need to format a CSV line. While working with files, proper handling of I/O exceptions is crucial. Kotlin, while offering null safety, still relies on ...
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) }
}
🌐
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
Top answer
1 of 8
21

[Edit October 2019] A couple of months after I wrote this answer, Koyama Kenta wrote a Kotlin targeted library which can be found at https://github.com/doyaaaaaken/kotlin-csv and which looks much better to me than opencsv.

Example usage: (for more info see the github page mentioned)

import com.github.doyaaaaaken.kotlincsv.dsl.csvReader

fun main() {
    csvReader().open("src/main/resources/test.csv") {
        readAllAsSequence().forEach { row ->
            //Do something
            println(row) //[a, b, c]
        }
    }
}

For a complete minimal project with this example, see https://github.com/PHPirates/kotlin-csv-reader-example

Old answer using opencsv:

As suggested, it is convenient to use opencsv. Here is a somewhat minimal example:

// You can of course remove the .withCSVParser part if you use the default separator instead of ;
val csvReader = CSVReaderBuilder(FileReader("filename.csv"))
        .withCSVParser(CSVParserBuilder().withSeparator(';').build())
        .build()

// Maybe do something with the header if there is one
val header = csvReader.readNext()

// Read the rest
var line: Array<String>? = csvReader.readNext()
while (line != null) {
    // Do something with the data
    println(line[0])

    line = csvReader.readNext()
}

As seen in the docs when you do not need to process every line separately you can get the result in the form of a Map:

import com.opencsv.CSVReaderHeaderAware
import java.io.FileReader

fun main() {
    val reader = CSVReaderHeaderAware(FileReader("test.csv"))
    val resultList = mutableListOf<Map<String, String>>()
    var line = reader.readMap()
    while (line != null) {
        resultList.add(line)
        line = reader.readMap()
    }
    println(resultList)
    // Line 2, by column name
    println(resultList[1]["my column name"])
}

Dependency for Gradle: compile 'com.opencsv:opencsv:4.6' or for Gradle Kotlin DSL: compile("com.opencsv:opencsv:4.6") (as always, check for latest version in docs).

2 of 8
9

In terms of easiness, kotlin written csv library is better.

For example, you can write code in DSL like way with below library that I created:

https://github.com/doyaaaaaken/kotlin-csv

csvReader().open("test.csv") {
    readAllAsSequence().forEach { row ->
        //Do something with the data
        println(row)
    }
}
🌐
DataFrame Help
kotlin.github.io › dataframe › csv-tsv.html
CSV / TSV | DataFrame
Requires the dataframe-csv module, which is included by default in the general dataframe artifact and in %use dataframe for Kotlin Notebook. You can read a DataFrame from a CSV or TSV file (via a file path or URL) using the readCsv() or readTsv() methods...