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();
        } 
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.

View Code