Methods for exporting CSV files using Java generics and reflection

  • 2020-04-01 03:38:31
  • OfStack

This article illustrates how to export CSV files using Java generics and reflection. Share with you for your reference. The details are as follows:

There is a requirement to export the data to CSV file in the project, because different classes have different properties. For the sake of simple code, generics and reflection of Java are applied, and a function is written to complete the export function.

public <T> void saveFile(List<T> list, String outFile) throws IOException {
        if (list == null || list.isEmpty()) {
            return;
        }
        if (StringUtils.isEmpty(outFile)) {
            throw new IllegalArgumentException("outfile is null");
        }
        boolean isFirst = true;
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new FileWriter(outFile));
            for (T t : list) {
                StringBuilder sb1 = new StringBuilder();
                StringBuilder sb2 = new StringBuilder();
                Class clazz = (Class) t.getClass();
                Field[] fs = clazz.getDeclaredFields();
                for (int i = 0; i < fs.length; i++) {
                    Field f = fs[i];
                    f.setAccessible(true);
                    try {
                        if (isFirst) {
                            sb1.append(f.getName());
                            sb1.append(",");
                        }
                        Object val = f.get(t);
                        if (val == null) {
                            sb2.append("");
                        } else {
                            sb2.append(val.toString());
                        }
                        sb2.append(",");
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                if (isFirst) {
                    out.write(sb1.toString());
                    isFirst = false;
                    out.newLine();
                }
                out.write(sb2.toString());
                out.newLine();
            }
        } catch (IOException e1) {
            throw e1;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e2) {
                throw e2;
            }
        }
}

I hope this article has been helpful to your Java programming.


Related articles: