Skip to content

Instantly share code, notes, and snippets.

@tuesd4y
Created May 12, 2018 09:34
Show Gist options
  • Save tuesd4y/bd8b71a8080b2f89214fb194b0883f45 to your computer and use it in GitHub Desktop.
Save tuesd4y/bd8b71a8080b2f89214fb194b0883f45 to your computer and use it in GitHub Desktop.
Helper for writing simple csv files
package at.triply.eventoverview.api
import java.io.File
class CsvFileHelper(val file: File) {
companion object {
val SEPERATOR = ";"
}
private fun createIfNotExists() {
if (!file.exists()) {
file.mkdirs()
file.createNewFile()
}
}
init {
createIfNotExists()
}
fun <T> writeData(data: List<T>, columns: List<CsvColumn<T>>, seperator: String = SEPERATOR) {
val headers = columns.map(CsvColumn<T>::header).joinToString(seperator)
val lines = data.map { item ->
columns.joinToString(seperator) {
it.encodeValue(item).run {
this as? String ?: it.toString()
}
}
}
file.bufferedWriter()
.apply {
write(headers)
newLine()
lines.forEach {
write(it)
newLine()
}
flush()
}
.close()
}
class CsvColumn<in T>(val header: String, private val encoder: (T) -> Any) {
fun encodeValue(value: T): Any {
return encoder(value)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment