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

前端 未结 10 930
终归单人心
终归单人心 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 07:19

    I can't speak for opencsv, but this is easily achievable using Super CSV, which has two different readers that support partial reading (ignoring columns), as well as reading into a Javabean. CsvDozerBeanReader is even capable of deep and index-based mapping, so you can map to nested fields.

    We (the Super CSV team) have just released version 2.0.0, which is available from Maven central or SourceForge.

    Update

    Here's an example (based on the test in the GitHub project you've created), that uses Super CSV instead of opencsv. Note the CSV preferences needed the surroundingSpacesNeedQuotes flag enabled as your example CSV file isn't valid (it has spaces between the fields - spaces are considered part of the data in CSV).

    ICsvBeanReader beanReader = null;
    try {
        beanReader = new CsvBeanReader(
                new InputStreamReader(
                        ClassLoader.getSystemResourceAsStream("test.csv")),
                new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE)
                        .surroundingSpacesNeedQuotes(true).build());
    
        List columnsToMap = Arrays.asList("fname", "telephone", "id");
    
        // read the CSV header (and set any unwanted columns to null)
        String[] header = beanReader.getHeader(true);
        for (int i = 0; i < header.length; i++) {
            if (!columnsToMap.contains(header[i])) {
                header[i] = null;
            }
        }
    
        Person person;
        while ((person = beanReader.read(Person.class, header)) != null) {
            System.out.println(person);
        }
    
    } finally {
        beanReader.close();
    }
    

提交回复
热议问题