OpenCSV不会写bean记录

时间:2017-11-28 14:25:21

标签: java opencsv

我刚开始为我的项目使用OpenCSV。运行此代码后,在我的桌面上创建了“test.csv”文件,但它是空的。我在哪里做错了?

public class test {
    List<MockBean> testData = new ArrayList<MockBean>();

    public static void main(String[] args) {
        try {
            List<MockBean> testData = new ArrayList<MockBean>();
            MockBean mb = new MockBean();
            mb.setName("kyle");
            mb.setOrderNumber("abc123456");
            mb.setNum(123);
            testData.add(mb);
            mb = new MockBean();
            mb.setName("jimmy");
            mb.setOrderNumber("def098765");
            mb.setNum(456);
            testData.add(mb);

            Writer writer = new FileWriter("C:\\Users\\ali.gumusoglu\\Desktop\\New folder\\test.csv");

            ColumnPositionMappingStrategy mappingStrategy = 
                    new ColumnPositionMappingStrategy();
            mappingStrategy.setType(MockBean.class);

            StatefulBeanToCsvBuilder<MockBean> builder = new StatefulBeanToCsvBuilder(writer);

            StatefulBeanToCsv beanWriter = builder
                    .withMappingStrategy(mappingStrategy)
                    .withSeparator('#')
                    .withQuotechar('\'')
                    .build();
            beanWriter.write(testData);
            System.out.println("CSV File written successfully!!!");


        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

}

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您是否将注释放入bean类? 例如,

@CsvBindByPosition(position = 0)
private String name;

答案 1 :(得分:0)

我通过在bean类中实现getters方法解决了这个问题。