jobin
jobin

Reputation: 2798

How to write bean to CSV using OpenCSV without converting to String[]?

I have a large array of a bean that needs to be written to a CSV file. I am trying to use OpenCSV but all the examples I see on the web ask me to convert the bean (POJO) that I have to a string array. I don't want to do this since this would mean I will have to go through the million beans and convert each of those beans to String[] which would be a very memory-expensive process.

This is the piece of code I have right now for doing this:

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

Is there a way I can avoid the conversion to String[] and use the list of beans that I have to write to a CSV file?

Upvotes: 5

Views: 18944

Answers (2)

Scott Conway
Scott Conway

Reputation: 983

Jobin, seriously, if you are using OpenCSV then use the BeanToCsv or the newer StatefulBeanToCsv. It will save your sanity.

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

Upvotes: 7

Andreas
Andreas

Reputation: 159086

You call writeNext() in a loop, converting one bean at a time. Not memory-expensive at all.

Upvotes: 1

Related Questions