zoukankan      html  css  js  c++  java
  • 应用Java泛型和反射导出CSV文件

    项目中有需求要把数据导出为CSV文件,因为不同的类有不同的属性,为了代码简单,应用Java的泛型和反射,写了一个函数,完成导出功能。

    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;
                }
            }
        }
  • 相关阅读:
    Redis12:客户端
    Redis11:事件
    Redis10:RDB持久化与AOF持久化
    Redis09:过期时间与删除策略、redis中的特殊线程
    Redis08:redis中的对象与存储形式
    Redis07:底层:基数树radix tree
    Redis06:底层:跳跃链表skiplist
    C++基础知识:异常处理
    C++基础知识:STL简介
    C++基础知识:泛型编程
  • 原文地址:https://www.cnblogs.com/wardensky/p/4161127.html
Copyright © 2011-2022 走看看