[2019 年 10 月编辑]在我写完这个答案几个月后,Koyama Kenta wrote a Kotlin targeted library 可以在 https://github.com/doyaaaaaken/kotlin-csv 找到,对我来说它看起来比 opencsv 好得多。
使用示例:(有关更多信息,请参阅提到的 github 页面)
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]
}
}
}
有关此示例的完整最小项目,请参阅https://github.com/PHPirates/kotlin-csv-reader-example
使用 opencsv 的旧答案:
按照建议,使用opencsv 很方便。下面是一个小例子:
// 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()
}
如docs 中所见,当您不需要单独处理每一行时,您可以得到 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"])
}
Gradle 的依赖项:compile 'com.opencsv:opencsv:4.6' 或 Gradle Kotlin DSL:compile("com.opencsv:opencsv:4.6")(与往常一样,请检查 docs 中的最新版本)。