OpenCSV - How to map selected columns to Java Bean regardless of order?

前端 未结 10 935
终归单人心
终归单人心 2020-11-30 06:38

I have a CSV file with the following columns: id, fname, telephone, lname, address.

I have a P

10条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 06:59

    Recent versions of OpenCSV deprecate the method parse(X, Y) and it's recommenced to use BeanBuilder instead, so the top answer is out of date.

    try {
        CsvToBeanBuilder beanBuilder = new CsvToBeanBuilder<>(new InputStreamReader(new FileInputStream("your.csv")));
    
        beanBuilder.withType(PersonCSV.class);
        // build methods returns a list of Beans
        beanBuilder.build().parse().forEach(e -> log.error(e.toString()));
    
    } catch (FileNotFoundException e) {
        log.error(e.getMessage(), e);
    }
    

    This methods allows you to clean up the code and remove MappingStrategy (you can still use it if you like spaghetti), so you can annotate your CSV class as follows:

    @CsvDate("dd/MM/yyyy hh:mm:ss")
    @CsvBindByName(column = "Time Born", required = true)
    private Date birthDate;
    

提交回复
热议问题