我正在写一个简单的导入应用程序,需要读取CSV文件,在网格中显示结果,并在另一个网格中显示CSV文件的损坏行。
有没有内置的库或者类似pythonic的简单方法?
我是在android上做的。
发布于 2019-03-10 23:34:48
编辑2019年10月
在我写下这个答案几个月后,
Koyama Kenta写了一个Kotlin目标库
可在以下位置找到
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? = csvReader.readNext()
while (line != null) {
// Do something with the data
println(line[0])
line = csvReader.readNext()
}
中可以看到
文档
当您不需要单独处理每一行时,您可以以Map的形式获得结果:
import com.opencsv.CSVReaderHeaderAware
import java.io.FileReader
fun main() {
val reader = CSVReaderHeaderAware(FileReader("test.csv"))
val resultList = mutableListOf>()
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的依赖性:
或者对于Gradle Kotlin DSL:
(如往常一样,请查看以下地址中的最新版本
文档
)。
发布于 2019-08-27 13:24:30
就易用性而言,kotlin编写的csv库更好。
例如,您可以使用我创建的以下库以类似于DSL的方式编写代码:
https://github.com/doyaaaaaken/kotlin-csv
csvReader().open("test.csv") {
readAllAsSequence().forEach { row ->
//Do something with the data
println(row)
}
}
发布于 2017-05-19 12:07:06
使用
opencsv
..。
这将会对读取CSV文件起到护身符的作用。
就记录损坏的行而言,您可以使用以下逻辑来完成此操作。
while(input.hasNextLine())
{
try
{
//execute commands by reading them using input.nextLine()
}
catch (ex: UserDefinedException)
{
//catch/log the exceptions you're throwing
// log the corrupted line the continue to next iteration
}
}
希望这能有所帮助。
https://stackoverflow.com/questions/44061143
复制相似问题