freemark工具類簡單使用
阿新 • • 發佈:2020-12-08
FreeMarker 是一款模板引擎: 即一種基於模板和要改變的資料, 並用來生成輸出文字(HTML網頁,電子郵件,配置檔案,原始碼等)的通用工具。
它不是面向終端使用者的,而是一個Java類庫,是一款程式設計師可以嵌入他們所開發產品的元件。
所需要的pom依賴
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>${freemarker.version}</version> </dependency>
工具類程式碼:
package com.common.base.utils; import java.io.*; import java.util.Locale; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; /** * @Auther: tony_t_peng * @Date: 2020-12-08 11:25 * @Description: */ public class FreeMarkerUtil { /** ** @param fileName 要讀取的檔名,包括檔案字尾名 * * @param item 傳入的map * * @param filePath 要讀取的檔案路徑 */ public static String generateString(String fileName, String templatePath, Map<String, Object> data) throws IOException { StringWriter out = new StringWriter(); process(fileName,templatePath,data,out); return out.getBuffer().toString(); } public static void generateFile(String fileName, String templatePath, Map<String, Object> data,File outFile) throws IOException { Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")); process(fileName,templatePath,data,out); } private static void process(String fileName, String templatePath,Map<String, Object> data, Writer out) throws IOException { try { // 通過Template可以將模板檔案輸出到相應的流 Template template = getTemplate(fileName, templatePath); template.process(data, out); out.flush(); } catch (Exception e){ e.printStackTrace(); }finally { if(out!=null){ out.close(); } } } private static Template getTemplate(String fileName, String templatePath){ try { // 通過Freemaker的Configuration讀取相應的ftl Configuration cfg = new Configuration(); cfg.setEncoding(Locale.CHINA, "utf-8"); // 設定去哪裡讀取相應的ftl模板檔案 cfg.setDirectoryForTemplateLoading(new File(templatePath)); // 在模板檔案目錄中找到名稱為name的檔案 Template temp = cfg.getTemplate(fileName); return temp; } catch (IOException e) { e.printStackTrace(); } return null; } }
單元測試程式碼:
String IDPS_TEMPLATE_NAME="CN.D.MANULIFE.TEMPLATE.ftl"; //模板檔名
String filePath = getClass().getResource("/tempalte/freemark/").getPath(); //模板資料夾地址
File file = new File(OUT_FILE_PATH+"CN.D.MANULIFE.DBSCOVR.txt"); //輸出檔案物件
FreeMarkerUtil.generateFile(IDPS_TEMPLATE_NAME,filePath,buildCoverageData(asOfDt),file);//buildCoverageData封裝要給map,用以存放物件
ftl 模板程式碼 示例:
${header!""} <#list items as item> ${item.field1!""}${item.field2!""}
</#list> ${trailer!""}
${item.field1!""}是非空判斷,如果沒有非空判斷,null的情況下會報錯