我使用jackson-dataformat-csv库。我想解析CSV文件。我有这个代码:

 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);
        }

我想从该文件中获取列名。但是我不知道该怎么做。我尝试:
csvSchema._columns

但是,它是空的对象。我也这样:
csvSchema.column(0)

我得到错误:
Method threw 'java.lang.ArrayIndexOutOfBoundsException' exception.

显然,columns对象为空。为什么?如何从CSV获取列名数组?

最佳答案

如果需要列名,可以将它们作为Map返回的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());

09-11 19:51