Kotlin – Read CSV File Line by Line

Kotlin – Read CSV File Line by Line

Reading a CSV (Comma-Separated Values) file line by line in Kotlin is an effective way to process large files without consuming excessive memory. This approach involves reading and processing each line of the CSV file individually.

To read a CSV file line by line, read the file into a File object, and then use File.forEachLine() function to process the file line by line.

In this tutorial, we will go through the process of reading a CSV file line by line using Kotlin, with an example.

Steps to Read a CSV File Line by Line in Kotlin

To read a CSV file line by line in Kotlin, follow these steps:

  1. Import the File class from the java.io package.
  2. Create a File object that points to your CSV file.
  3. Use the forEachLine function to iterate through each line of the file.
  4. For each line, split it into tokens using the split() function with a comma (or other delimiter) as the argument.
  5. Process each line as required for your specific application.

Kotlin Example Program to Read a CSV File Line by Line

In the following example program, we will read a CSV file named 'data.csv' line by line and prints each line’s tokens to the standard output.

Main.kt

import java.io.File

fun main() {
    val filePath = "dir1/data.csv" // Replace with your CSV file path
    val file = File(filePath)

    file.forEachLine { line ->
        val tokens = line.split(",")
        // Process tokens here
        println(tokens)
    }
}

data.csv

apple,25,red
guava,50,green

Output

[apple, 25, red]
[guava, 50, green]

The output will display each line’s tokens, separated by commas. The exact output will depend on the contents of your CSV file.

Summary

In this Kotlin tutorial, we explored how to read a CSV file line by line. This method is particularly useful for processing large CSV files efficiently, allowing for each line to be handled separately.