程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 運用Java泛型和反射導出CSV文件的辦法

運用Java泛型和反射導出CSV文件的辦法

編輯:關於JAVA

運用Java泛型和反射導出CSV文件的辦法。本站提示廣大學習愛好者:(運用Java泛型和反射導出CSV文件的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是運用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;
            }
        }
}

願望本文所述對年夜家的Java法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved