I using jackson-dataformat-csv
library. I want parse CSV
file. I have this code:
CsvMapper csvMapper = new CsvMapper();
CsvSchema csvSchema = csvMapper.typedSchemaFor(Map.class).withHeader();
List<Map<String, String>> csvRows;
try {
MappingIterator<Map<String, String>> it = csvMapper.readerFor(Map.class)
.with(csvSchema.withColumnSeparator(';'))
.readValues(file.getInputStream());
csvRows = it.readAll();
} catch (Exception ex) {
log.error("Unable to read csv document: ", ex);
}
I want get column names from this file. But I don't understand how to make it. I try:
csvSchema._columns
But, It is empty object. Too I make this:
csvSchema.column(0)
I get error:
Method threw 'java.lang.ArrayIndexOutOfBoundsException' exception.
Obviously, columns object is empty. Why? How I get array of column names from CSV
?
the fields are not in CsvSchema
until you get the Parser from MappingIterator
a working example:
CsvSchema schema = (CsvSchema) objectMappingIterator.getParser().getSchema();
Iterator<CsvSchema.Column> iterator = schema.iterator();
while (iterator.hasNext()) {
CsvSchema.Column next = iterator.next();
next.getName();
}
If you need column names you have them as keys in Map
returned by MappingIterator
:
CsvMapper csvMapper = new CsvMapper();
CsvSchema csvSchema = csvMapper.typedSchemaFor(Map.class).withHeader();
MappingIterator<Map<String, String>> it = csvMapper.readerFor(Map.class)
.with(csvSchema.withColumnSeparator(','))
.readValues(csvFile);
System.out.println("Column names: " + it.next().keySet());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With