README

kotlin-csv

​
​
​
​
​​
​
​
Pure Kotlin CSV Reader/Writer.

Design goals

1. Simple interface

  • easy to setup
  • use DSL so easy to read

2. Automatic handling of I/O

  • in Java, we always need to close file. but it's boilerplate code and not friendly for non-JVM user.
  • provide interfaces which automatically close file without being aware.

3. Multiplatform

  • kotlin multiplatform project

Usage

Download

Gradle

1
//gradle kotlin DSL
2
implementation("com.github.doyaaaaaken:kotlin-csv-jvm:1.2.0") //for JVM platform
3
implementation("com.github.doyaaaaaken:kotlin-csv-js:1.2.0") //for Kotlin JS platform
4
​
5
//gradle groovy DSL
6
implementation 'com.github.doyaaaaaken:kotlin-csv-jvm:1.2.0' //for JVM platform
7
implementation 'com.github.doyaaaaaken:kotlin-csv-js:1.2.0' //for Kotlin JS platform
Copied!

Maven

1
<dependency>
2
<groupId>com.github.doyaaaaaken</groupId>
3
<artifactId>kotlin-csv-jvm</artifactId>
4
<version>1.2.0</version>
5
</dependency>
6
<dependency>
7
<groupId>com.github.doyaaaaaken</groupId>
8
<artifactId>kotlin-csv-js</artifactId>
9
<version>1.2.0</version>
10
</dependency>
Copied!
​kscript​
1
@file:DependsOn("com.github.doyaaaaaken:kotlin-csv-jvm:1.2.0") //for JVM platform
2
@file:DependsOn("com.github.doyaaaaaken:kotlin-csv-js:1.2.0")
3
​
4
//for Kotlin JS platform
Copied!

Examples

CSV Read examples

Simple case
You can read csv file from String, java.io.File or java.io.InputStream object. No need to do any I/O handling. (No need to call use, close and flush method.)
1
// read from `String`
2
val csvData: String = "a,b,c\nd,e,f"
3
val rows: List<List<String>> = csvReader().readAll(csvData)
4
​
5
// read from `java.io.File`
6
val file: File = File("test.csv")
7
val rows: List<List<String>> = csvReader().readAll(file)
Copied!
Read with header
1
val csvData: String = "a,b,c\nd,e,f"
2
val rows: List<Map<String, String>> = csvReader().readAllWithHeader(csvData)
3
println(rows) //[{a=d, b=e, c=f}]
Copied!
Read as Sequence
Sequence type allows to execute lazily. It starts to process each rows before reading all row data.
See detail about Sequence type on Kotlin official document.
1
csvReader().open("test1.csv") {
2
readAllAsSequence().forEach { row: List<String> ->
3
//Do something
4
println(row) //[a, b, c]
5
}
6
}
7
​
8
csvReader().open("test2.csv") {
9
readAllWithHeaderAsSequence().forEach { row: Map<String, String> ->
10
//Do something
11
println(row) //{id=1, name=doyaaaaaken}
12
}
13
}
Copied!
NOTE:readAllAsSequence and readAllWithHeaderAsSequence methods can only be called within the open lambda block. The input stream is closed after the open lambda block.
Read line by line
If you want to handle line-by-line, you can do it by using open method. Use open method and then use readNext method inside nested block to read row.
1
csvReader().open("test.csv") {
2
readNext()
3
}
Copied!
Read in a Suspending Function
1
csvReader().openAsync("test.csv") {
2
val container = mutalbeListOf<List<String>>()
3
delay(100) //other suspending task
4
readAllAsSequence().asFlow().collect { row ->
5
delay(100) // other suspending task
6
container.add(row)
7
}
8
}
Copied!
Note: openAsync can be and only be accessed through a coroutine or another suspending function
Customize
When you create CsvReader, you can choose read options:
1
// this is tsv reader's option
2
val tsvReader = csvReader {
3
charset = "ISO_8859_1"
4
quoteChar = '"'
5
delimiter = '\t'
6
escapeChar = '\\'
7
}
Copied!
Opton
default value
description
charset
UTF-8
Charset encoding. The value must be supported by java.nio.charset.Charset.
quoteChar
"
Character used to quote fields.
delimiter
,
Character used as delimiter between each field. Use "\t" if reading TSV file.
escapeChar
"
Character to escape quote inside field string. Normally, you don't have to change this option. See detail comment on ICsvReaderContext.
skipEmptyLine
false
Whether to skip or error out on empty lines.
skipMissMatchedRow
false
Whether to skip an invalid row (different number of fields from other rows) or throw an exception.
autoRenameDuplicateHeaders
false
Whether to auto rename duplicate headers or throw an exception.

CSV Write examples

Simple case
You can start writing csv in one line, no need to do any I/O handling (No need to call use, close and flush method.):
1
val rows = listOf(listOf("a", "b", "c"), listOf("d", "e", "f"))
2
csvWriter().writeAll(rows, "test.csv")
3
​
4
// if you'd append data on the tail of the file, assign `append = true`.
5
csvWriter().writeAll(rows, "test.csv", append = true)
6
​
7
// You can also write into OutpusStream.
8
csvWriter().writeAll(rows, File("test.csv").outputStream())
Copied!
You can also write a csv file line by line by open method:
1
val row1 = listOf("a", "b", "c")
2
val row2 = listOf("d", "e", "f")
3
​
4
csvWriter().open("test.csv") {
5
writeRow(row1)
6
writeRow(row2)
7
writeRow("g", "h", "i")
8
writeRows(listOf(row1, row2))
9
}
Copied!
Write in a Suspending Function
1
val rows = listOf(listOf("a", "b", "c"), listOf("d", "e", "f")).asSequence()
2
csvWriter().openAsync(testFileName) {
3
delay(100) //other suspending task
4
rows.asFlow().collect {
5
delay(100) // other suspending task
6
writeRow(it)
7
}
8
}
Copied!
long-running write (manual control for file close)
If you want to close a file writer manually for performance reasons (e.g. streaming scenario), you can use openAndGetRawWriter and get a raw CsvFileWriter. DO NOT forget to close the writer!
1
val row1 = listOf("a", "b", "c")
2
​
3
@OptIn(KotlinCsvExperimental::class)
4
val writer = csvWriter().openAndGetRawWriter("test.csv")
5
writer.writeRow(row1)
6
writer.close()
Copied!
Customize
When you create a CsvWriter, you can choose write options.
1
val writer = csvWriter {
2
charset = "ISO_8859_1"
3
delimiter = '\t'
4
nullCode = "NULL"
5
lineTerminator = "\n"
6
outputLastLineTerminator = true
7
quote {
8
mode = WriteQuoteMode.ALL
9
char = '\''
10
}
11
}
Copied!
Option
default value
description
charset
UTF-8
Charset encoding. The value must be supported by java.nio.charset.Charset.
delimiter
,
Character used as delimiter between each fields. Use "\t" if reading TSV file.
nullCode
(empty string)
Character used when a written field is null value.
lineTerminator
\r
Character used as line terminator.
outputLastLineTerminator
true
Output line break at the end of file or not.
quote.char
"
Character to quote each fields.
quote.mode
CANONICAL
Quote mode. - CANONICAL: Not quote normally, but quote special characters (quoteChar, delimiter, line feed). This is the specification of CSV. - ALL: Quote all fields. - NON_NUMERIC: Quote non-numeric fields. (ex. 1,"a",2.3)

Links

Documents
Libraries which use kotlin-csv

Miscellaneous

🀝 Contributing

Contributions, issues and feature requests are welcome! If you have questions, ask away in Kotlin Slack's kotlin-csv room.

πŸ’» Development

1
git clone [email protected]:doyaaaaaken/kotlin-csv.git
2
cd kotlin-csv
3
./gradlew check
Copied!

Show your support

Give a ⭐️ if this project helped you!

πŸ“ License

Copyright Β© 2019 doyaaaaaken. This project is licensed under Apache 2.0.
​
This project is inspired ❀️ by scala-csv​
This README was generated with ❀️ by readme-md-generator​
Last modified 2mo ago