【freemaker】之FreeMakerUtil工具类

时间:2022-10-24 12:09:09

Freemaker生成文件常用工具类

public class FreemakerUtil {
private static FreemakerUtil util;
private static Configuration cfg;
private FreemakerUtil(){
}
//做成单例模式
public synchronized static FreemakerUtil getInstance(String pname){
if(util==null){
cfg = new Configuration();
cfg.setClassForTemplateLoading(FreemakerUtil.class,pname);
cfg.setDefaultEncoding("UTF-8");
util=new FreemakerUtil();
}
return util;
}
//获取模版
public Template getTemplate(String fname){
try {
return cfg.getTemplate(fname);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//控制台输出
public void print(Map<String,Object> map,String fname){
try {
getTemplate(fname).process(map,new PrintWriter(System.out));
} catch (Exception e) {
e.printStackTrace();
}
}
//输出到指定位置
public void fprint(Map<String,Object> map,String fname,String outpath){
try {
getTemplate(fname).process(map, new FileWriter(outpath));
} catch (Exception e) {
e.printStackTrace();
}
}
}