应用Java泛型和反射导出CSV文件的方法
本文实例讲述了应用Java泛型和反射导出CSV文件的方法。分享给大家供大家参考。具体如下:
项目中有需求要把数据导出为CSV文件,因为不同的类有不同的属性,为了代码简单,应用Java的泛型和反射,写了一个函数,完成导出功能。
public<T>voidsaveFile(List<T>list,StringoutFile)throwsIOException{ if(list==null||list.isEmpty()){ return; } if(StringUtils.isEmpty(outFile)){ thrownewIllegalArgumentException("outfileisnull"); } booleanisFirst=true; BufferedWriterout=null; try{ out=newBufferedWriter(newFileWriter(outFile)); for(Tt:list){ StringBuildersb1=newStringBuilder(); StringBuildersb2=newStringBuilder(); Classclazz=(Class)t.getClass(); Field[]fs=clazz.getDeclaredFields(); for(inti=0;i<fs.length;i++){ Fieldf=fs[i]; f.setAccessible(true); try{ if(isFirst){ sb1.append(f.getName()); sb1.append(","); } Objectval=f.get(t); if(val==null){ sb2.append(""); }else{ sb2.append(val.toString()); } sb2.append(","); }catch(IllegalArgumentException|IllegalAccessExceptione){ e.printStackTrace(); } } if(isFirst){ out.write(sb1.toString()); isFirst=false; out.newLine(); } out.write(sb2.toString()); out.newLine(); } }catch(IOExceptione1){ throwe1; }finally{ try{ if(out!=null){ out.close(); } }catch(IOExceptione2){ throwe2; } } }
希望本文所述对大家的Java程序设计有所帮助。