qa-prevention-gwj/src/main/java/com/zcloud/util/Freemarker.java

81 lines
2.6 KiB
Java
Raw Normal View History

2023-11-07 09:32:12 +08:00
package com.zcloud.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* Freemarker
* luoxiaobao
* www.qdkjchina.com
*/
public class Freemarker {
/**
* ()
* @param ftlName
*/
public static void print(String ftlName, Map<String,Object> root, String ftlPath) throws Exception{
try {
Template temp = getTemplate(ftlName, ftlPath); //通过Template可以将模板文件输出到相应的流
temp.process(root, new PrintWriter(System.out));
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param ftlName ftl
* @param root map
* @param outFile
* @param filePath
*/
public static void printFile(String ftlName, Map<String,Object> root, String outFile, String filePath, String ftlPath) throws Exception{
try {
File file = new File(PathUtil.getProjectpath() + filePath + outFile);
if(!file.getParentFile().exists()){ //判断有没有父路径,就是判断文件整个路径是否存在
file.getParentFile().mkdirs(); //不存在就全部创建
}
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
Template template = getTemplate(ftlName, ftlPath);
template.process(root, out); //模版输出
out.flush();
out.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param ftlName
*/
public static Template getTemplate(String ftlName, String ftlPath) throws Exception{
try {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); //通过Freemaker的Configuration读取相应的ftl
cfg.setEncoding(Locale.CHINA, "utf-8");
cfg.setDirectoryForTemplateLoading(new File(PathUtil.getProjectpath()+"/admin/template/ftl/"+ftlPath)); //设定去哪里读取相应的ftl模板文件
Template temp = cfg.getTemplate(ftlName); //在模板文件目录中找到名称为name的文件
return temp;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}