Pure Kotlin CSV Reader/Writer.
- easy to setup
- use DSL so easy to read
- 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.
- kotlin multiplatform project
//gradle kotlin DSL
implementation("com.github.doyaaaaaken:kotlin-csv-jvm:1.1.0") //for JVM platform
implementation("com.github.doyaaaaaken:kotlin-csv-js:1.1.0") //for Kotlin JS platform
//gradle groovy DSL
implementation 'com.github.doyaaaaaken:kotlin-csv-jvm:1.1.0' //for JVM platform
implementation 'com.github.doyaaaaaken:kotlin-csv-js:1.1.0' //for Kotlin JS platform
<dependency>
<groupId>com.github.doyaaaaaken</groupId>
<artifactId>kotlin-csv-jvm</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.github.doyaaaaaken</groupId>
<artifactId>kotlin-csv-js</artifactId>
<version>1.1.0</version>
</dependency>
@file:DependsOn("com.github.doyaaaaaken:kotlin-csv-jvm:1.1.0") //for JVM platform
@file:DependsOn("com.github.doyaaaaaken:kotlin-csv-js:1.1.0") //for Kotlin JS platform
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.)
// read from `String`
val csvData: String = "a,b,c\nd,e,f"
val rows: List<List<String>> = csvReader().readAll(csvData)
// read from `java.io.File`
val file: File = File("test.csv")
val rows: List<List<String>> = csvReader().readAll(file)
val csvData: String = "a,b,c\nd,e,f"
val rows: List<Map<String, String>> = csvReader().readAllWithHeader(csvData)
println(rows) //[{a=d, b=e, c=f}]
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.
csvReader().open("test1.csv") {
readAllAsSequence().forEach { row: List<String> ->
//Do something
println(row) //[a, b, c]
}
}
csvReader().open("test2.csv") {
readAllWithHeaderAsSequence().forEach { row: Map<String, String> ->
//Do something
println(row) //{id=1, name=doyaaaaaken}
}
}
NOTE:readAllAsSequence
and readAllWithHeaderAsSequence
methods
can only be called within the open
lambda block.
The input stream is closed after the open
lambda block.
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.
csvReader().open("test.csv") {
readNext()
}