kotlin-csv
Pure Kotlin Multiplatform CSV reader and writer.
Setup
Gradle (Kotlin DSL)
implementation("com.jsoizo:kotlin-csv:2.1.0")
The multiplatform artifact resolves JVM, JS, Kotlin/Wasm, and supported
Kotlin/Native variants from Kotlin Multiplatform projects. Published
Native targets are macosArm64, iosArm64, iosSimulatorArm64,
linuxX64, linuxArm64, and mingwX64. Published Wasm targets are
and .
Single-platform Gradle projects can also depend on the platform artifact
directly, for example kotlin-csv-jvm, kotlin-csv-js,
kotlin-csv-wasm-js, kotlin-csv-macosarm64, or kotlin-csv-linuxx64.
Gradle (Groovy DSL)
implementation 'com.jsoizo:kotlin-csv:2.1.0'
Maven
SNAPSHOT builds
Snapshots of the next development version are published to
Sonatype Central Portal Snapshots from the active development branch.
SNAPSHOTs are unstable and may change at any time, but they let you try in-progress changes early.
Add the snapshots repository to your build, then declare the dependency with the corresponding -SNAPSHOT version
(see the active development branch's build.gradle.kts for the current value, for example 2.0.0-SNAPSHOT).
Gradle (Kotlin DSL)
dependencyResolutionManagement {
repositories {
mavenCentral()
maven("https://central.sonatype.com/repository/maven-snapshots/") {
mavenContent { snapshotsOnly() }
}
}
}
implementation("com.jsoizo:kotlin-csv:<VERSION>-SNAPSHOT")
Quick start
The DSL builders return reusable, stateless instances; create them once and
share them across calls.
import com.jsoizo.kotlincsv.csvReader
import com.jsoizo.kotlincsv.csvWriter
import com.jsoizo.kotlincsv.reader.CsvNullFieldIndicator
import com.jsoizo.kotlincsv.reader.readFromFile
import com.jsoizo.kotlincsv.reader.withHeader
import com.jsoizo.kotlincsv.writer.WriteQuoteMode
import com.jsoizo.kotlincsv.writer.writeToFile
val reader = csvReader()
val writer = csvWriter()
Read
val rows: List<List<String>> = reader.readAll("a,b,c\nd,e,f")
reader.readFromFile(File("data.csv")) { rows ->
rows.forEach { println(it) }
}
reader.readFromFile(File("data.csv")) { rows ->
val records = rows.withHeader().toList()
println(records.first()["id"])
}
val nullableRows = csvReader {
nullFieldIndicator = CsvNullFieldIndicator.EMPTY_SEPARATORS
}.readAllNullable()
reader.readFromFile(...) accepts String paths, kotlinx.io.files.Path,
and (on JVM) java.io.File. The block receives a cold
; and friends short-circuit cleanly
without parsing the rest of the file. For in-memory streams use
(commonMain ) or
(JVM ).
Write
rows = listOf(
listOf(, , ),
listOf(, , ),
)
csv: String = writer.writeAll(rows)
record: String = writer.writeRow(listOf(, ))
nullableRecord: String = writer.writeNullableRow(listOf(, , ))
writer.writeToFile(rows, File())
nullableCsv = csvWriter {
quoteMode = WriteQuoteMode.ALL
}.writeAllNullable(listOf(listOf(, , )))
For rows received one at a time, for example from an existing channel, append
each record directly to your existing writer:
for (row in channel) {
bufferedWriter.append(writer.writeNullableRow(row))
}
writeRow and writeNullableRow return strings and do not manage the channel
or output resource. With the default outputLastLineTerminator = true, each
record already ends in the configured terminator; do not append an extra newline.
With that option disabled, callers are responsible for separating records.
A quoted field may itself contain line breaks.
writer.writeToFile(...) accepts String paths, kotlinx.io.files.Path,
and (on JVM) java.io.File. For in-memory streams use
(commonMain ) or
(JVM ). Both
and are accepted as the row
source.
Configuration
Reader and writer share a CsvDialect value object that holds the four
characters defining the CSV format itself: delimiter, quoteChar,
escapeChar, lineTerminator. Format-independent policies stay on the
respective Config.
val tsvReader = csvReader {
dialect = CsvDialect.TSV
skipEmptyLine = true
}
val customWriter = csvWriter {
dialect = CsvDialect(delimiter = ';', escapeChar = '\\')
quoteMode = WriteQuoteMode.ALL
}
Quoted fields preceded by spaces or tabs can be read explicitly:
val rows = csvReader { ignoreLeadingWhitespace = true }
.readAll("a, \"b\"")
For an immutable configuration, use config.withIgnoreLeadingWhitespace(true).
The original constructor and copy keep their five arguments; copying a
configuration preserves its whitespace option.
The default remains strict. This option does not trim unquoted fields, accept
spaces after a closing quote, or consume a configured delimiter/quote/escape
as whitespace. Other whitespace characters are not ignored.
CsvFieldNumDifferentException.rowNum counts CSV rows after reader filters
such as skipEmptyLine; it is not a physical source line number.
Nullable reader APIs (readNullable, readAllNullable, and nullable I/O
overloads) return String? values. withNullableHeader() keeps header keys
as non-null String; a null-looking empty header is treated as the empty
header name "", while data values remain nullable.
Charset is JVM-only and is passed as an argument on the I/O call:
reader.readFromFile(File("data.csv"), charset = "windows-31j") { it.toList() }
writer.writeToFile(rows, File("out.csv"), charset = "UTF-16LE")
commonMain and JS overloads are UTF-8 only.
kotlin-csv's JVM I/O does not throw when the charset cannot map a
character. "windows-31j" and "Shift_JIS" write ? in its place. On
read, bytes the charset cannot decode become U+FFFD.
For Japanese text, use "windows-31j" (alias "MS932") rather than Java's
"Shift_JIS" (alias "SJIS"):
BOM stripping on read defaults to ON (matches Excel-produced files):
reader.readFromFile(File("data.csv"), options = CsvReadIoOptions(stripBom = false))
writer.writeToFile(rows, File("out.csv"), options = CsvWriteIoOptions(prependBom = true))
Recipes
Exchange files with Excel
Keep the default dialect, CsvDialect.RFC4180. If the recipient's Excel
uses ; as the list separator, use CsvDialect(delimiter = ';'). The main
choice is the encoding. Pick it by what the recipient can read:
writer.writeToFile(rows, "out.csv", options = CsvWriteIoOptions(prependBom = true))
writer.writeToFile(rows, File("out.csv"), charset = "windows-31j")
Windows-31J writes characters such as 𠮷 and emoji as ? without an
error. Replace 〜 (U+301C) and three similar characters first, as
described in Configuration. Do not combine
charset = "windows-31j" with prependBom = true. Windows-31J cannot
encode the BOM, so the file starts with ?.
To read a CSV file saved by Excel, keep the default UTF-8 for a UTF-8 file
and pass charset = "windows-31j" for a Windows-31J file. The reader drops a
leading BOM by default.
Exchange files with PostgreSQL COPY
With and the default option, PostgreSQL writes as
an unquoted empty field and an empty string as . To keep that
difference, set and read with a
nullable API such as . Write nullable rows with
. The default mode writes both and
as an unquoted empty field, so loads the empty strings as
.
val pgReader = csvReader {
nullFieldIndicator = CsvNullFieldIndicator.EMPTY_SEPARATORS
}
val pgWriter = csvWriter {
dialect = CsvDialect(lineTerminator = "\n")
quoteMode = WriteQuoteMode.ALL
}
val csv = pgWriter.writeAllNullable(listOf(listOf("1", null, "")))
pgReader.readAllNullable(csv)
More
- Migration from kotlin-csv 1.x:
see V2_MIGRATION_GUIDE.md.
Miscellaneous
🤝 Contributing
Contributions, issues and feature requests are welcome!
If you have questions, ask away in Kotlin Slack's kotlin-csv room.
💻 Development
git clone git@github.com:jsoizo/kotlin-csv.git
cd kotlin-csv
./gradlew check
📝 License
Copyright © 2024 jsoizo.
This project is licensed under Apache 2.0.
Acknowledgments
This project was originally created by @doyaaaaaken. The initial work and contributions are greatly appreciated.