Sling Academy
Home/Kotlin/Processing CSV Files Using Kotlin’s File API

Processing CSV Files Using Kotlin’s File API

Last updated: November 30, 2024

In this article, we will explore how to efficiently process CSV files using Kotlin’s File API. The flexibility and power of these API allow you to read, write, and manipulate CSV data seamlessly in a Kotlin application.

Getting Started with Kotlin’s File API

Kotlin's File API is included as part of the Kotlin standard library, and it provides several extensions around java.io.File class to handle file systems. To process CSV files, we ensure that our project has no special dependencies other than the JVM itself.

Reading CSV Files

To read a CSV file, you generally open the file, read its contents line-by-line, and parse it according to CSV format conventions.

Here is a basic example to read a CSV file:


import java.io.File

fun readCsv(fileName: String): List> {
    val file = File(fileName)
    return file.readLines()
        .map { line -> line.split(";") }
}

fun main() {
    val csvData = readCsv("data.csv")
    for (row in csvData) {
        println(row)
    }
}

Explanation:

  • File(fileName) creates a File object from the given path.
  • readLines() reads the file line by line and returns a list of strings.
  • Each line is split by the delimiter, ";", into a list representing a CSV row.

Writing to CSV Files

Writing to a CSV file in Kotlin is straightforward using the File API. Here, we'll see how you can transfer a list of data into a CSV format and write it to the file system.


fun writeCsv(fileName: String, data: List>) {
    val file = File(fileName)
    file.printWriter().use { out ->
        data.forEach { row ->
            out.println(row.joinToString(separator = ";"))
        }
    }
}

fun main() {
    val data = listOf(
        listOf("Name", "Age", "City"),
        listOf("Alice", "30", "New York"),
        listOf("Bob", "25", "Los Angeles")
    )
    writeCsv("output.csv", data)
}

Explanation:

  • A PrintWriter is used here, which provides buffering and convenient handling of character data output.
  • The joinToString() extension function converts an array or list into a string separated by specified characters, which is precisely what you need to format a CSV line.

Error Handling and Exceptions

While working with files, proper handling of I/O exceptions is crucial. Kotlin, while offering null safety, still relies on traditional try-catch blocks to handle potential file access related exceptions.


try {
    val data = readCsv("nonexistent.csv")
    data.forEach { println(it) }
} catch (e: Exception) {
    println("An error occurred: ")
    e.printStackTrace()
}

This code ensures that any file access or parsing anomalies do not cause abrupt application termination.

Conclusion

Handling CSV files in Kotlin with its File API provides an intuitive approach to manage data with the syntax we’ve explored. Whether reading or writing, you'll find these methods easy to adapt and integrate into your projects. Mastery of these techniques can greatly enhance the efficiency and reliability of your data-driven applications.

Next Article: Reading and Writing XML Files in Kotlin

Previous Article: How to Read and Write JSON Files in Kotlin

Series: Kotlin - File & OS

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin