Home > Back-end >  java 11 openCSV write to file only specific bean properties
java 11 openCSV write to file only specific bean properties

Time:10-05

How to write to csv file (using openCSV) only specific bean properties

i.e given the class

public class MyEntry {

private String propOne;
private Long propTwo;
private int propThree;
private String propFour;
private String propFive;
...
private String propFifteen;

//getters and setter omitted for brevity

}

There might be situation where I need to create a csv file with fields from propFour to propTen in other situations it might be a necessary to create a csv with all bean properties. There might be many situations that require different fields to be exported to csv file. How to achieve it without creating custom classes for different situations?

CodePudding user response:

You could create CSVWriter.java and use the reflection concept to read the attributes of your class. Remember call setAccesible(true) in order to access to private field from outside

Dummy object

import java.util.List;

public class Dummy {
  public static final List<String> GROUP_1 = List.of("prop1", "prop2");
  public static final List<String> GROUP_2 = List.of("prop1", "prop3");
  private String prop1;
  private Integer prop2;
  private String prop3;

  public String getProp1() {
      return prop1;
  }

  public Integer getProp2() {
      return prop2;
  }

  public String getProp3() {
    return prop3;
  }

  public void setProp1(String prop1) {
      this.prop1 = prop1;
  }

  public void setProp2(Integer prop2) {
      this.prop2 = prop2;
  }

  public void setProp3(String prop3) {
      this.prop3 = prop3;
  }
}

CSV Writer

import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

public class CSVWriter<T> {
    private List<T> dataList;

    CSVWriter(List<T> dataList){
        this.dataList = dataList;
    }

    public void setDataList(List<T> dataList) {
        this.dataList = dataList;
    }

    public List<T> getDataList() {
        return dataList;
    }

    void save(FileWriter fileWriter) {
        if(dataList == null) {
            throw new RuntimeException("the data was not initialized");
        }

        //TODO Write all attributes into csv file
    }

    void save(FileWriter fileWriter, List<String> attributeNames) throws NoSuchFieldException, IllegalAccessException, IOException {
        if(dataList == null) {
            throw new RuntimeException("the data was not initialized");
        }

        //TODO improve errors handle

        for (T data : dataList) {
            Class<?> c = data.getClass();
            for (String attribute : attributeNames) {
                Field field = c.getDeclaredField(attribute);
                String valueString = getValue(field, data);
                fileWriter.write(valueString   ",");
            }
            fileWriter.write("\n");
            fileWriter.flush();
        }

        fileWriter.close();
    }

    private String getValue(Field field, T data) throws IllegalAccessException {
        field.setAccessible(true); //due to private field
        return field.get(data).toString();
    }
}

How to use it?

public static void main(String[] args) throws Exception {
    List<Dummy> dummyList = new ArrayList<>();
    Dummy dummy1 = new Dummy();
    dummy1.setProp1("prop 1 value");
    dummy1.setProp2(2);
    dummy1.setProp3("prop 3 value");


    dummyList.add(dummy1);

    CSVWriter<Dummy> csvWriter = new CSVWriter<>(dummyList);

    csvWriter.save(new FileWriter("group1.csv"), Dummy.GROUP_1);
    csvWriter.save(new FileWriter("group2.csv"), Dummy.GROUP_2);
    System.out.println("Hello World!");
}

I know that you need to do it using OpenCSV. I never used the library before, but the concept should be the same one.

  • Related