Java泛型和反射导出CSV文件 应用Java泛型和反射导出CSV文件的方法
人气:1想了解应用Java泛型和反射导出CSV文件的方法的相关内容吗,在本文为您仔细讲解Java泛型和反射导出CSV文件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,泛型,反射,导出,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;
}
}
}
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程序设计有所帮助。
加载全部内容