OpenCSV CSV to JavaBean

前端 未结 2 923
一向
一向 2021-01-07 10:49

If I have a class with non-primitive public members and I want to populate them from a CSV file with OpenCSV, how can I do this? I notice that OpenCSV has some protected mem

2条回答
  •  鱼传尺愫
    2021-01-07 11:14

    Have you checked out the following FAQ question? It sounds to me like that's what you want to do. I could be mistaken though.

    Is there a way to bind my CSV file to a list of Javabeans?

    Yes there is.

    Kyle Miller added a new set of classes to allow you to bind a CSV file to a list of JavaBeans based on column name, column position, or a custom mapping strategy. You can find the new classes in the au.com.bytecode.opencsv.bean package. Here's how you can map to a java bean based on the field positions in your CSV file:

    ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy(); 
    strat.setType(YourOrderBean.class); 
    String[] columns = new String[] {"name", "orderNumber", "id"}; // the fields to bind do in your JavaBean 
    strat.setColumnMapping(columns); 
    CsvToBean csv = new CsvToBean(); 
    List list = csv.parse(strat, yourReader);
    

提交回复
热议问题