Introduction

Reading CSV files in Kotlin is a common requirement for various data processing tasks. A CSV (Comma Separated Values) file is simple, text-based, and widely used to represent tabular data. Despite its simplicity, handling CSV files correctly requires handling special cases, like escaped characters, multi-line fields, and missing values. This guide covers several standard methods to read CSV files in Kotlin, providing both the advantages and disadvantages of each approach.

Solutions

Solution 1: Using Kotlin’s readLines Method

Description:
You can use Kotlin’s standard library function readLines to read each line of a CSV file into a list of strings. This is a straightforward method but requires additional parsing logic to separate CSV columns and handle special cases like quoted fields.

Kotlin Code:

import java.io.File

fun readCsvUsingReadLines(fileName: String): List<List<String>> {
    val file = File(fileName)
    return file.readLines().map { it.split(",") }
}

fun main() {
    val csvData = readCsvUsingReadLines("sample.csv")
    csvData.forEach { println(it) }
}

Output:

[Name, Age, City]
[John Doe, 30, New York]
[Jane Smith, 25, Los Angeles]

Advantages:

  • Simple and easy to understand.
  • Uses Kotlin’s built-in libraries.

Disadvantages:

  • Does not handle quoted fields or embedded commas.
  • Requires additional parsing logic for complex CSV files.

Solution 2: Using OpenCSV Library

Description:
OpenCSV is a powerful library for reading and writing CSV files in Java and Kotlin. It provides robust support for quoted fields, custom delimiters, and more.

Kotlin Code:

import com.opencsv.CSVReader
import java.io.FileReader

fun readCsvUsingOpenCsv(fileName: String): List<Array<String>> {
    val reader = CSVReader(FileReader(fileName))
    return reader.use { it.readAll() }
}

fun main() {
    val csvData = readCsvUsingOpenCsv("sample.csv")
    csvData.forEach { println(it.joinToString(", ")) }
}

Output:

Name, Age, City
John Doe, 30, New York
Jane Smith, 25, Los Angeles

Advantages:

  • Handles quoted fields, embedded commas, and custom delimiters.
  • Simplifies CSV parsing with rich features.

Disadvantages:

  • Requires an additional library dependency.
  • Slightly more complex setup compared to using Kotlin’s standard functions.

Solution 3: Using Apache Commons CSV Library

Description:
Apache Commons CSV provides a powerful and flexible way to work with CSV files. It supports various CSV dialects (including Excel and MySQL) and offers high performance for reading and writing.

Kotlin Code:

import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVParser
import java.nio.file.Files
import java.nio.file.Paths

fun readCsvUsingApacheCommons(fileName: String): List<Map<String, String>> {
    val reader = Files.newBufferedReader(Paths.get(fileName))
    val csvParser = CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader())
    return csvParser.records.map { it.toMap() }
}

fun main() {
    val csvData = readCsvUsingApacheCommons("sample.csv")
    csvData.forEach { println(it) }
}

Output:

{Name=John Doe, Age=30, City=New York}
{Name=Jane Smith, Age=25, City=Los Angeles}

Advantages:

  • Comprehensive feature set for CSV parsing.
  • Automatically maps CSV fields to a header.

Disadvantages:

  • Requires an additional library dependency.
  • More complex API compared to other solutions.

Similar Topics

  1. Kotlin – How to Write a CSV File
  2. Kotlin – How to Parse JSON File
  3. Kotlin – How to Read Excel Files
  4. Kotlin – Working with XML Files
  5. Kotlin – Handling Large Files Efficiently
  6. Kotlin – How to Use Streams for File Processing
  7. Kotlin – Error Handling in File Operations
  8. Kotlin – Using Config Files in Kotlin Applications
  9. Kotlin – Reading Properties Files
  10. Kotlin – File I/O Best Practices
  11. Kotlin – Using Kotlin Coroutines for File Operations
  12. Kotlin – How to Securely Handle Files
  13. Kotlin – Memory Management During File Operations
  14. Kotlin – Utilizing Libraries for Data Parsing
  15. Kotlin – How to Log File Operations in Kotlin
  16. Kotlin – Handling Special Characters in Files
  17. Kotlin – How to Compress/Decompress Files
  18. Kotlin – Monitoring File Changes in Kotlin
  19. Kotlin – Building a CSV Reader Utility in Kotlin
  20. Kotlin – Common Pitfalls in File Handling