Kotlin – Read CSV File
To reading a CSV (Comma-Separated Values) file in Kotlin efficiently, you can use basic file reading functions along with string manipulation methods.
CSV files are commonly used for storing tabular data and can be easily processed line by line in Kotlin.
In this tutorial, we will go through the steps of reading a CSV file using Kotlin, and then an example program to read a CSV file and print it to output.
Steps to Read a CSV File in Kotlin
To read a CSV file in Kotlin, follow these steps:
- Import the
File
class from thejava.io
package. - Create a
File
object pointing to your CSV file. - Read the file line by line using a loop.
- Split each line into tokens using the
split()
function and a delimiter (commonly a comma). - Process each token as needed for your application.
Kotlin Example Program to Read a CSV File
In the following example, we read a CSV file named 'data.csv'
and process its contents.
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 vary depending on the content of your CSV file. Each line will be split into tokens based on the comma delimiter.
Summary
In this Kotlin tutorial, we covered how to read a CSV file using File operations and String operations, with an example.