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 ; } } |