Last active
July 19, 2018 22:02
-
-
Save jahunt1/051ffc065dd883b6d54e8cad9de23123 to your computer and use it in GitHub Desktop.
Parse CSV data in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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