DEV Community

loizenai
loizenai

Posted on

Kotlin – How to read/write CSV file with OpenCSV

https://grokonez.com/kotlin/kotlin-how-to-read-write-csv-file-with-opencsv-example

Kotlin – How to read/write CSV file with OpenCSV

In this tutorial, we're gonna look at Kotlin examples that read and write CSV file using OpenCSV.

I. Dependency

<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib</artifactId>
    <version>1.2.21</version>
</dependency>

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>4.0</version>
</dependency>

II. Write Data to CSV File

1. From String Array


var fileWriter = FileWriter("customer.csv")

csvWriter = CSVWriter(fileWriter,
        CSVWriter.DEFAULT_SEPARATOR,
        CSVWriter.NO_QUOTE_CHARACTER,
        CSVWriter.DEFAULT_ESCAPE_CHARACTER,
        CSVWriter.DEFAULT_LINE_END)
        
val data = arrayOf("ID","NAME","ADDRESS","AGE")
csvWriter.writeNext(data)

2. From List of Objects

More at:

https://grokonez.com/kotlin/kotlin-how-to-read-write-csv-file-with-opencsv-example

Kotlin – How to read/write CSV file with OpenCSV

Top comments (0)