欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

应用Java泛型和反射导出CSV文件的方法

程序员文章站 2024-03-01 10:15:58
本文实例讲述了应用java泛型和反射导出csv文件的方法。分享给大家供大家参考。具体如下: 项目中有需求要把数据导出为csv文件,因为不同的类有不同的属性,为了代码简单,...

本文实例讲述了应用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;
            }
        }
}

希望本文所述对大家的java程序设计有所帮助。