如何在csv列中写入String数组

时间:2018-11-29 17:31:57

标签: java file csv supercsv

public class bean {
  private String name;
  private String[] friends;
}

public void createSuperCSVFile(final List<VariantTO> data,
                               final File file) throws IOException {
    ICsvBeanWriter beanWriter = null;
    try {
        String[] header = {"name", "friends"};
        beanWriter = new CsvBeanWriter(new FileWriter(file), TAB_PREFERENCE);
        // write the header
        beanWriter.writeHeader(header);

        for (Object object: data) {
            beanWriter.write(object, header);
        }
    } finally {
        if( beanWriter != null ) {
            beanWriter.close();
        }
    }
}

我正在使用supercsv将具有字符串数组属性的POJO写入csv。 CsvBeanWriter只是将对象地址而不是其值写入列中。是否有任何设置可以正确映射该值?

EXPECTED
name    friends
john    dimitry,olaf,nett

ACTUAL
name    friends
john    [Ljava.lang.String;@50ccb5a3

1 个答案:

答案 0 :(得分:0)

解决方案是编写我自己的单元处理器。我编写了String []处理器,该处理器以逗号分隔的值作为字符串返回。

final CellProcessor[] PROCESSORS = new CellProcessor[] {
    new NotNull(),
    new ParseStringArray()
};

beanWriter = new CsvBeanWriter(new FileWriter(file), TAB_PREFERENCE);

for (Object object: data) {
    beanWriter.write(object, header, PROCESSORS);
}


class ParseStringArray extends CellProcessorAdaptor implements StringCellProcessor {
    @Override
    public <T> T execute(final Object value, final CsvContext context) {
        validateInputNotNull(value, context);
        String result;
        if (value instanceof String[]) {
            result = StringUtils.join((String[]) value, ",");
        } else {
            final String actualClassName = value.getClass().getName();
            throw new SuperCsvCellProcessorException(String.format(
                "the input value should be of type String array but is of type %s", actualClassName), context, this);
        }

        return next.execute(result, context);
    }
}