Files
Terrarum/src/net/torvald/CSVFetcher.kt
Song Minjae abf167d6b8 computer with term lib: somewhat works; new cobblestone texture
Former-commit-id: 8a1a21cc1ea874ec1c243cae7b1e920bdab3be4f
Former-commit-id: ee7aeb05896a36960050f0656764ccf477e5f90d
2016-09-14 20:28:43 +09:00

70 lines
2.0 KiB
Kotlin

package net.torvald
import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVParser
import org.apache.commons.csv.CSVRecord
import java.io.IOException
import java.io.InputStreamReader
import java.nio.file.FileSystems
import java.nio.file.Files
/**
* Created by minjaesong on 16-02-16.
*/
object CSVFetcher {
private var csvString: StringBuffer? = null
@Throws(IOException::class)
operator fun invoke(csvFilePath: String): List<CSVRecord> {
csvString = StringBuffer() // reset buffer every time it called
readCSVasString(csvFilePath)
println("Reading CSV $csvFilePath")
val csvParser = CSVParser.parse(
csvString!!.toString(),
CSVFormat.DEFAULT.withIgnoreSurroundingSpaces()
.withHeader()
.withIgnoreEmptyLines()
.withDelimiter(';')
.withCommentMarker('#')
.withNullString("N/A")
.withRecordSeparator('\n')
)
val csvRecordList = csvParser.records
csvParser.close()
return csvRecordList
}
fun readFromString(csv: String): List<CSVRecord> {
val csvParser = CSVParser.parse(
csv,
CSVFormat.DEFAULT.withIgnoreSurroundingSpaces()
.withHeader()
.withIgnoreEmptyLines()
.withDelimiter(';')
.withCommentMarker('#')
.withNullString("N/A")
.withRecordSeparator('\n')
)
val csvRecordList = csvParser.records
csvParser.close()
return csvRecordList
}
@Throws(IOException::class)
fun readCSVasString(path: String): String {
csvString = StringBuffer()
Files.lines(FileSystems.getDefault().getPath(path)).forEach(
{ s -> csvString!!.append("$s\n") }
)
return csvString!!.toString()
}
}