Read the CSV string in Kotlin

I am writing a simple import application and should read the CSV file, show the result in the grid and show the damaged lines of the CSV file in another grid.

Is there a built-in lib for it or some simple pythonic-like path?

I am doing this on android.

+9
source share
4 answers

Use opencsv .

It will work like a charm when reading a CSV file.

Regarding the registration of damaged lines, you can do this using this logic.

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
    }
}

Hope this helps.

+5
source

[ 2019 ] , , 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<String>? = csvReader.readNext()
while (line != null) {
    // Do something with the data
    println(line[0])

    line = csvReader.readNext()
}

, , :

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") ( , ).

+4

I used net.sourceforge.javacsv with my Kotlin code to parse CSV files. This is the java library, but in kotlin, working with it is pretty simple:

val reader = CsvReader("/path/to/file.csv").apply {
  trimWhitespace = true
  skipEmptyRecords = true
  readHeaders()
}

while (reader.readRecord()) {
  // do whatever
}
+3
source

In terms of simplicity, the csv library written in kotlin is better.

For example, you can write code in DSL, for example, using the library below:

https://github.com/doyaaaaaken/kotlin-csv

csvReader().open("test.csv") {
    readAllAsSequence().forEach { row ->
        //Do something with the data
        println(row)
    }
}
+1
source

Source: https://habr.com/ru/post/1017376/


All Articles