fuookami.ospf.kotlin.utils.serialization.CSV.kt Maven / Gradle / Ivy
package fuookami.ospf.kotlin.utils.serialization
import java.io.*
import kotlinx.serialization.*
import kotlinx.serialization.csv.*
import kotlinx.serialization.builtins.*
@OptIn(InternalSerializationApi::class)
inline fun readFromCSV(path: String): List {
return readFromCSV(T::class.serializer(), path)
}
@OptIn(ExperimentalSerializationApi::class)
fun readFromCSV(serializer: KSerializer, path: String): List {
val file = File(path)
val csv = Csv {
hasHeaderRecord = true
ignoreUnknownColumns = true
}
return csv.decodeFromString(ListSerializer(serializer), String(file.readBytes()).replace("\r\n", "\n"))
}
@OptIn(InternalSerializationApi::class)
inline fun readFromCSV(stream: InputStream): List {
return readFromCSV(T::class.serializer(), stream)
}
@OptIn(ExperimentalSerializationApi::class)
fun readFromCSV(serializer: KSerializer, stream: InputStream): List {
val csv = Csv {
hasHeaderRecord = true
ignoreUnknownColumns = true
}
return csv.decodeFromString(ListSerializer(serializer), String(stream.readBytes()).replace("\r\n", "\n"))
}
@OptIn(InternalSerializationApi::class)
inline fun writeCSVToFile(path: String, value: List) {
return writeCSVToFile(path, T::class.serializer(), value)
}
@OptIn(ExperimentalSerializationApi::class)
fun writeCSVToFile(path: String, serializer: KSerializer, value: List) {
val csv = Csv {
hasHeaderRecord = true
ignoreUnknownColumns = true
}
File(path).writeText(csv.encodeToString(ListSerializer(serializer), value))
}