应用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程序设计有所帮助。
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短