How to read and write CSV files in Kotlin
How to read and write CSV files in Kotlin.
Here's a step-by-step tutorial on how to read and write CSV files in Kotlin:
Reading CSV Files
Step 1: Import the necessary libraries
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
Step 2: Create a function to read the CSV file
fun readCSVFile(filePath: String) {
try {
val reader = BufferedReader(FileReader(filePath))
var line: String?
// Read each line of the file
while (reader.readLine().also { line = it } != null) {
// Process the line (e.g., split into columns)
val columns = line!!.split(",")
// Use the data as needed (e.g., print to console)
for (column in columns) {
println(column)
}
}
reader.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
Step 3: Call the function and provide the file path
val filePath = "path/to/your/file.csv"
readCSVFile(filePath)
Writing CSV Files
Step 1: Import the necessary libraries
import java.io.BufferedWriter
import java.io.FileWriter
import java.io.IOException
Step 2: Create a function to write data to a CSV file
fun writeCSVFile(filePath: String, data: List<List<String>>) {
try {
val writer = BufferedWriter(FileWriter(filePath))
// Write each row of data to the file
for (row in data) {
writer.write(row.joinToString(","))
writer.newLine()
}
writer.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
Step 3: Call the function and provide the file path and data
val filePath = "path/to/your/file.csv"
val data = listOf(
listOf("Name", "Age", "Email"),
listOf("John Doe", "25", "john@example.com"),
listOf("Jane Smith", "30", "jane@example.com")
)
writeCSVFile(filePath, data)
That's it! You now know how to read and write CSV files in Kotlin. Feel free to customize the code based on your specific requirements.