OpenCSV从4.1升级到5.7.1后,为什么无法将Bean写入CSV

new9mtju  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(197)

我正在使用OpenCSV将Java bean写入CSV文件。以下是代码片段:

public void generateCSVFile(List<?> domains, String[] columns, String fileName) {
    try {
    final FileWriter writer = new FileWriter(fileName);
    CSVWriter csvWriter = new CSVWriter(writer);
    csvWriter.writeNext(columns);
    if (CollectionUtils.isNotEmpty(domains)) {
        ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
        mappingStrategy.setType(Class.forName(domains.get(0).getClass().getTypeName()));
        mappingStrategy.setColumnMapping(columns);
        StatefulBeanToCsvBuilder<?> builder = new StatefulBeanToCsvBuilder(
                csvWriter);
        StatefulBeanToCsv beanWriter = builder.withMappingStrategy(mappingStrategy).build();
        beanWriter.write(domains);
        csvWriter.close();
        writer.close();
    }
    }
    catch(Exception e){
       LOG.error("Exception occured while generating CSV file : {}", e)
     }
}

这在opencsv 4.1版中运行得很好。它生成了一个CSV文件,其中的标题和列按照我传递列的顺序(String[])。最近,我将版本更新到了5.7.1,之后它生成的CSV文件只有标题而没有数据。它生成的是一个空文件,生成的文件中只有标题。
我试过使用HeaderColumnNameMappingStrategy,它生成的文件中包含数据,但是属性是升序的,属性是大写的,因为这是默认行为。
有没有办法让ColumnPositionMappingStrategy在5.7.1版中像在4.1版中一样工作?

6psbrbz9

6psbrbz91#

此方法适用于OpenCSV版本4.1和5.7:

序列化

public static <T> void writeToCSV(String location, Class<T> type, List<T> records, String[] columns)
          throws IOException, CsvRequiredFieldEmptyException, CsvDataTypeMismatchException {

    ColumnPositionMappingStrategy<T> mappingStrategy = new ColumnPositionMappingStrategy<>();
    mappingStrategy.setType(type);
    mappingStrategy.setColumnMapping(columns);
    try (Writer writer = new FileWriter(location)) {
      StatefulBeanToCsv<T> beanToCsv = new StatefulBeanToCsvBuilder<T>(writer)
                      .withMappingStrategy(mappingStrategy)
                      .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                      .build();
      beanToCsv.write(records);
    }
}

用法示例

String[] columns = new String[]{"a", "b"};
List<Bean> objects = List.of(new Bean("A1", "B1"),
                             new Bean("A2", "B2"));
String location = "beans.csv";

try {
    CSVUtils.writeToCSV(location, Bean.class, objects, columns);
} catch (IOException | CsvRequiredFieldEmptyException | CsvDataTypeMismatchException e) {
    e.printStackTrace();
}

假设类Bean有两个字符串属性ab
我用Java 8、11和17测试了上面的代码。

相关问题