3

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 ?

Clyde Barrow
  • 1,924
  • 8
  • 30
  • 60

1 Answers1

0

This worked for me:

return mapper.readerForListOf(Map.class)
    .with(schema)
    .with(CsvParser.Feature.WRAP_AS_ARRAY) // <-- This.
    .readTree(content);
Fabricio
  • 7,705
  • 9
  • 52
  • 87