Created
May 12, 2018 09:34
-
-
Save tuesd4y/bd8b71a8080b2f89214fb194b0883f45 to your computer and use it in GitHub Desktop.
Helper for writing simple csv files
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
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