CSV
suggest changeCSV (comma-separated values) is the most common format for exchanging tabular data: spreadsheet exports, database dumps, reports, and data feeds. It looks trivial, but real-world CSV has quoting rules that a naive parser gets wrong.
This article covers:
- why
line.split(",")breaks - the RFC 4180 quoting rules
- a small, correct CSV parser and writer in plain Kotlin
- the kotlin-csv library for reading, writing, and streaming
- mapping rows to data classes
- alternatives: Apache Commons CSV, Jackson CSV, kotlinx-serialization-csv
Why split(",") breaks
fun main() {
val line = "1,\"Smith, John\",42"
println(line.split(","))
// [1, "Smith, John", 42] <- 4 fields, not 3, and the quotes are still there
}
Splitting on commas fails when:
- a field contains a comma:
"Smith, John" - a field contains a quote:
"He said ""hi""" - a field contains a newline, so a single record spans multiple lines. This also means you can't process CSV by calling
readLines()and parsing each line on its own.
RFC 4180 rules
RFC 4180 is the closest thing CSV has to a standard:
- records are separated by line breaks (
\r\nofficially, but parsers should also accept\n) - fields are separated by commas
- a field that contains a comma, a double quote, or a line break must be enclosed in double quotes
- a double quote inside a quoted field is escaped by doubling it:
"" - the first record may be a header with column names
id,name,note
1,"Smith, John","He said ""hi"""
2,Ann,"line one
line two"
3,,
In practice you'll also see ; as the delimiter (common in European locales where , is the decimal separator), tabs (TSV), and files that start with a UTF-8 BOM.
A hand-written parser
A correct parser is a small state machine: either you're inside a quoted field or you're not. It works on the whole text rather than line by line, so newlines inside quotes are handled:
fun parseCsv(text: String, delimiter: Char = ','): List<List<String>> {
val rows = mutableListOf<List<String>>()
var row = mutableListOf<String>()
val field = StringBuilder()
var inQuotes = false
var i = 0
fun endField() { row.add(field.toString()); field.clear() }
fun endRow() { endField(); rows.add(row); row = mutableListOf() }
while (i < text.length) {
val c = text[i]
if (inQuotes) {
if (c == '"') {
if (i + 1 < text.length && text[i + 1] == '"') {
field.append('"') // escaped quote ""
i++
} else {
inQuotes = false
}
} else {
field.append(c)
}
} else {
when (c) {
'"' -> inQuotes = true
delimiter -> endField()
'\r' -> {
if (i + 1 < text.length && text[i + 1] == '\n') i++
endRow()
}
'\n' -> endRow()
else -> field.append(c)
}
}
i++
}
require(!inQuotes) { "Unterminated quoted field" }
// last record without a trailing newline
if (field.isNotEmpty() || row.isNotEmpty()) endRow()
return rows
}
A hand-written writer
Writing is simpler: quote a field only if it needs it, and double any quotes inside it:
fun escapeCsv(value: String, delimiter: Char = ','): String {
val needsQuotes = value.any { it == delimiter || it == '"' || it == '\n' || it == '\r' }
return if (needsQuotes) "\"" + value.replace("\"", "\"\"") + "\"" else value
}
fun toCsv(rows: List<List<String>>, delimiter: Char = ','): String =
rows.joinToString(separator = "\r\n", postfix = "\r\n") { row ->
row.joinToString(delimiter.toString()) { escapeCsv(it, delimiter) }
}
fun main() {
val input = "id,name,note\r\n1,\"Smith, John\",\"He said \"\"hi\"\"\"\r\n" +
"2,Ann,\"line one\nline two\"\r\n3,,\r\n"
val rows = parseCsv(input)
rows.forEach { println(it) }
// [id, name, note]
// [1, Smith, John, He said "hi"]
// [2, Ann, line one
// line two]
// [3, , ]
println(toCsv(rows) == input) // true: the round trip is lossless
}
This is fine for small files and scripts. For large files, streaming, BOM handling, and configurable dialects, use a library.
kotlin-csv
kotlin-csv is a pure-Kotlin multiplatform CSV library with a small DSL.
// build.gradle.kts
dependencies {
implementation("com.github.doyaaaaaken:kotlin-csv-jvm:1.10.0")
}
The examples use 1.10.0, the last release under the original com.github.doyaaaaaken group id. Newer versions are published as com.jsoizo:kotlin-csv-jvm with the package renamed to com.jsoizo.kotlincsv; check the changelog before upgrading.
Reading
csvReader() returns a reader; readAll gives a List<List<String>> and readAllWithHeader gives a List<Map<String, String>> keyed by header names. Both accept a String, a File, or an InputStream:
import com.github.doyaaaaaken.kotlincsv.dsl.csvReader
import java.io.File
fun main() {
val csv = """
id,name,email
1,"Smith, John",john@example.com
2,Ann,ann@example.com
""".trimIndent()
val rows: List<List<String>> = csvReader().readAll(csv)
println(rows[1]) // [1, Smith, John, john@example.com]
val records: List<Map<String, String>> = csvReader().readAllWithHeader(csv)
for (r in records) {
println("${r["id"]}: ${r["name"]} <${r["email"]}>")
}
// from a file
val fromFile = csvReader().readAllWithHeader(File("users.csv"))
}
Configuring the dialect
val reader = csvReader {
charset = "UTF-8"
delimiter = ';'
quoteChar = '"'
skipEmptyLine = true
}
val rows = reader.readAll(File("export-de.csv"))
Streaming large files
readAll* loads everything into memory. For big files, use open, which keeps the file open for the duration of the lambda and gives you a lazy Sequence:
import com.github.doyaaaaaken.kotlincsv.dsl.csvReader
import java.io.File
fun main() {
var total = 0.0
csvReader().open(File("orders.csv")) {
readAllWithHeaderAsSequence().forEach { row: Map<String, String> ->
total += row.getValue("amount").toDouble()
}
}
println("Total: $total")
// without a header: readAllAsSequence() yields List<String>
csvReader { skipEmptyLine = true }.open(File("raw.csv")) {
readAllAsSequence()
.take(10)
.forEach(::println)
}
}
The sequence is only valid inside the open block; don't return it out of the lambda.
Writing
import com.github.doyaaaaaken.kotlincsv.dsl.csvWriter
import java.io.File
fun main() {
val rows = listOf(
listOf("id", "name", "note"),
listOf("1", "Smith, John", "He said \"hi\""),
)
csvWriter().writeAll(rows, File("out.csv"))
// streaming write, row by row
csvWriter { lineTerminator = "\n" }.open(File("big.csv")) {
writeRow("id", "value")
for (i in 1..1_000_000) {
writeRow(i, i * i)
}
}
// append to an existing file
csvWriter().writeAll(listOf(listOf("3", "Bob", "")), File("out.csv"), append = true)
}
The writer quotes and escapes fields as needed.
Mapping rows to data classes
CSV fields are always strings, so you convert them to typed values yourself. Using the header map keeps the code independent of column order:
import com.github.doyaaaaaken.kotlincsv.dsl.csvReader
import com.github.doyaaaaaken.kotlincsv.dsl.csvWriter
import java.io.File
import java.time.LocalDate
data class Order(val id: Int, val customer: String, val amount: Double, val date: LocalDate)
fun Map<String, String>.toOrder() = Order(
id = getValue("id").toInt(),
customer = getValue("customer"),
amount = getValue("amount").toDouble(),
date = LocalDate.parse(getValue("date")),
)
fun Order.toRow(): List<Any> = listOf(id, customer, amount, date)
fun main() {
val orders: List<Order> = csvReader()
.readAllWithHeader(File("orders.csv"))
.map { it.toOrder() }
val big = orders.filter { it.amount > 100.0 }
csvWriter().open(File("big-orders.csv")) {
writeRow("id", "customer", "amount", "date")
writeRows(big.map { it.toRow() })
}
}
getValue throws NoSuchElementException when a column is missing, and toInt() throws NumberFormatException on bad data. For user-supplied files, consider toIntOrNull() and collecting errors with the row number instead of failing on the first bad row.
Alternatives
Apache Commons CSV
The battle-tested Java library, with predefined formats (DEFAULT, RFC4180, EXCEL, TDF, MYSQL, ...) and streaming via Iterable<CSVRecord>:
// implementation("org.apache.commons:commons-csv:1.12.0")
import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVPrinter
import java.io.File
fun main() {
val format = CSVFormat.DEFAULT.builder()
.setHeader()
.setSkipHeaderRecord(true)
.build()
File("orders.csv").bufferedReader().use { reader ->
for (record in format.parse(reader)) {
println("${record["id"]} ${record["customer"]}")
}
}
File("out.csv").bufferedWriter().use { writer ->
CSVPrinter(writer, CSVFormat.DEFAULT.builder().setHeader("id", "name").build()).use { p ->
p.printRecord(1, "Smith, John")
}
}
}
Jackson CSV
If you already use Jackson for JSON, jackson-dataformat-csv together with jackson-module-kotlin maps rows directly to data classes using a CsvSchema:
// implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.17.2")
// implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.17.2")
import com.fasterxml.jackson.dataformat.csv.CsvMapper
import com.fasterxml.jackson.dataformat.csv.CsvSchema
import com.fasterxml.jackson.module.kotlin.kotlinModule
import java.io.File
data class User(val id: Int, val name: String)
fun main() {
val mapper = CsvMapper().registerModule(kotlinModule())
val schema = CsvSchema.emptySchema().withHeader()
val users: List<User> = mapper.readerFor(User::class.java)
.with(schema)
.readValues<User>(File("users.csv"))
.readAll()
println(users)
}
kotlinx-serialization-csv
Community CSV formats for kotlinx.serialization (for example de.brudaswen.kotlinx.serialization:kotlinx-serialization-csv) let you annotate a data class with @Serializable and encode or decode lists of it, the same way you would with JSON. They're a good fit if your project already uses kotlinx.serialization.
Gotchas
- Never build CSV with string templates.
"$id,$name"breaks as soon asnamecontains a comma or quote. Always escape. - Encoding and BOM. Excel often writes UTF-8 with a BOM (
), which ends up glued to the first header name ("id"). Strip it, or use a library that does. - Excel and delimiters. Excel uses the system list separator, which is
;in many locales. If users open your file in Excel, test with their locale. - CSV injection. Fields starting with
=,+,-, or@may be run as formulas when opened in a spreadsheet. If you export user-supplied data for spreadsheet users, prefix such values with'. - Numbers and dates. CSV has no types. Agree on a format (ISO 8601 dates,
.as the decimal separator) and parse explicitly.