Reputation: 2102
I want to read csv file to List of strings. I also want it to trim whitespaces and allow trailing comma. My csv file looks like this:
abcdefghijklmno ,
pqrstuwzabcdefh,
ijklmnopqrstuwyz,
zabcdefghijklmopqr,
And when I try to parse it using my method:
fun parseCsv(inputStream: InputStream): List<String> {
val mapper = CsvMapper().enable(CsvParser.Feature.TRIM_SPACES).enable(CsvParser.Feature.ALLOW_TRAILING_COMMA)
val schema = CsvSchema
.emptySchema()
.withLineSeparator("\n")
.withColumnSeparator(',')
.withQuoteChar('"')
return try {
mapper
.readerFor(String::class.java)
.with(schema)
.readValues<String>(inputStream)
.readAll()
} catch (e: IOException ) {
logger.error("Error parsing file", e)
emptyList()
} catch (e: NoSuchElementException) {
throw FileParsingError(e)
}
}
I get:
expected == actual
| | |
| | [abcdefghijklmno, ]
| false
[abcdefghijklmno, pqrstuwzabcdefh, ijklmnopqrstuwyz, zabcdefghijklmopqr]
How to fix it ?
Upvotes: 3
Views: 1463
Reputation: 7925
This worked for me:
return mapper.readerForListOf(Map.class)
.with(schema)
.with(CsvParser.Feature.WRAP_AS_ARRAY) // <-- This.
.readTree(content);
Upvotes: 0