如何使用OpenCSV将bean写入CSV而不转换为String []?

时间:2017-04-10 14:39:46

标签: java csv opencsv

我有一大堆需要写入CSV文件的bean。我正在尝试使用OpenCSV,但我在网上看到的所有示例都要求我将我拥有的bean(POJO)转换为字符串数组。我不想这样做,因为这意味着我将不得不通过百万个bean并将每个bean转换为String [],这将是一个非常耗费内存的过程。

这是我现在所做的一段代码:

private static void writeRowsToCsv(Path filePath, List<MyBean> rows)
        throws IOException {

    StringWriter writer = new StringWriter();
    CSVWriter csvWriter = new CSVWriter(writer, '#', '\'');
    ColumnPositionMappingStrategy mappingStrategy =
            new ColumnPositionMappingStrategy();
    mappingStrategy.setType(MyBean.class);
    List<String[]> rowsInStringArray = convertBeanToStringArray(rows)
    csvWriter.writeAll(rowsInStringArray);
}

有没有办法可以避免转换为String[]并使用我必须写入CSV文件的bean列表?

2 个答案:

答案 0 :(得分:4)

Jobin,严肃地说,如果您使用的是OpenCSV,请使用BeanToCsv或更新的StatefulBeanToCsv。它会拯救你的理智。

private static void writeRowsToCsv(Path filePath, List<MyBean> rows)
        throws IOException {

    StringWriter writer = new StringWriter();
    ColumnPositionMappingStrategy mappingStrategy =
            new ColumnPositionMappingStrategy();
    mappingStrategy.setType(MyBean.class);

    StatefulBeanToCsvBuilder<MyBean> builder = new StatefulBeanToCsvBuilder(writer);
    StatefulBeanToCsv beanWriter = builder
              .withMappingStrategy(mappingStrategy)
              .withSeparator('#')
              .withQuotechar('\'')
              .build();

    beanWriter.write(rows);
}

答案 1 :(得分:1)

您在循环中调用writeNext(),一次转换一个bean。根本不是内存昂贵的。