OpenCsv writes wrong column names with BeanToCsv + HeaderColumnNameTranslateMappingStrategy

妖精的绣舞 提交于 2019-11-29 11:03:02
Krishnaraj

Looking at the source code of BeanToCsv, the processHeader(...) method does nothing with the supplied headers. Your only option is to create a custom strategy ( to avoid CSVReader ) and a custom BeanToCsv as below

 

public class CustomBean {
   ...
   public static void main(String[] args) {
     ...
     HeaderColumnNameTranslateMappingStrategy strategy = new CustomStrategy<CustomBean>();
     strategy.setType(CustomBean.class);
     strategy.setColumnMapping(mapping);
     ...

     BeanToCsv bean = new CustomBeanToCsv<CustomBean>();
     ...
   }

   static class CustomStrategy<T> extends HeaderColumnNameTranslateMappingStrategy {

    @Override
    public void setColumnMapping(Map columnMapping) {
        super.setColumnMapping(columnMapping);
        header = new String[columnMapping.size()];
        int i = 0;
        for (Map.Entry entry : columnMapping.entrySet()) {
            header[i] = entry.getKey().toUpperCase();
            i++;
        }
    }

     public String[] getHeader() {
         return header;
     }
   }

   static class CustomBeanToCsv<T> extends BeanToCsv {
     @Override
     protected String[] processHeader(MappingStrategy mapper) throws IntrospectionException {
         if (mapper instanceof CustomStrategy) {
             return ((CustomStrategy) mapper).getHeader();
         } else {
             return super.processHeader(mapper);
         }
     }
   }
}

 

I have been using openCSV for five years now and I am still learning stuff about it. The issue is that the HeaderColumnNameMappingStrategy and HeaderColumnNameTranslateMappingStrategy were made for the CsvToBean. It wants a file to read to get the header out to see where the reader should read from.

For the BeanToCsv class use the ColumnPositionMappingStrategy class. You give it the class you are mapping and a list of the columns you want to map and it does the rest for you.

Here is a little test method I wrote that worked.

public void createUsingBeanToCsv(int numRecords, FileWriter fos) {
    List<SmallRecord> smallRecords = new ArrayList<>(numRecords);
    for (int i = 0; i < numRecords; i++) {
        smallRecords.add(SmallRecordGenerator.createRecord(i));
    }

    BeanToCsv<SmallRecord> beanToCsv = new BeanToCsv<>();
    ColumnPositionMappingStrategy<SmallRecord> strategy = new ColumnPositionMappingStrategy<>();
    strategy.setType(SmallRecord.class);
    String[] columns = new String[]{"bigDecimal_1", "name_1", "intNumber_1"};
    strategy.setColumnMapping(columns);

    beanToCsv.write(strategy, fos, smallRecords);

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!