Skip to content

Instantly share code, notes, and snippets.

@jahunt1
Last active July 19, 2018 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jahunt1/051ffc065dd883b6d54e8cad9de23123 to your computer and use it in GitHub Desktop.
Save jahunt1/051ffc065dd883b6d54e8cad9de23123 to your computer and use it in GitHub Desktop.
Parse CSV data in Kotlin
class CsvParser {
fun parseLine(line: String) : List<String> = parseLine(line, ',')
fun parseLine(line: String, separator: Char) : List<String> {
val result = mutableListOf<String>()
val builder = StringBuilder()
var quotes = 0
for (ch in line) {
when {
ch == '\"' -> {
quotes++
builder.append(ch)
}
(ch == '\n') || (ch == '\r') -> {}
(ch == separator) && (quotes % 2 == 0) -> {
result.add(builder.toString())
builder.setLength(0)
}
else -> builder.append(ch)
}
}
if (builder.length > 0) result.add(builder.toString())
return result
}
}
// --- USAGE ---
//val lines = Files.readAllLines(csvFile.toPath(), StandardCharsets.UTF_8)
// for (i in 1 until lines.size) {
// val values = csvParser.parseLine(lines[i])
// // do something useful with the values
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment