FreemarkerUtil工具类封装

package org.ftl.utl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import freemarker.template.Version;

public class FreemarkerUtil {
 private static FreemarkerUtil fk;;
 private static Configuration cfg;

 private FreemarkerUtil() {
 }
 /**
  *
  * @param freemarkerVersionNo freemarker的版本号
  * @param templatePath 模版加载路径
  * @return
  */
 public static FreemarkerUtil getInstance(String freemarkerVersionNo, String templatePath) {
  if (null == fk) {
   cfg = new Configuration(new Version(freemarkerVersionNo));
   cfg.setClassForTemplateLoading(FreemarkerUtil.class, templatePath);
   fk=new FreemarkerUtil();
  }
  return fk;
 }
 /**
  *
  * @param templateName 根据模版名称加载对应模版
  * @return
  */
 private Template getTemplate(String templateName){
  try {
   return cfg.getTemplate(templateName);
  } catch (TemplateNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (MalformedTemplateNameException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  return null;
 }
 
 /**
  *
  * @param dataModel 数据模型
  * @param templateName 输出模版
  */
 public void sprint(Map<String, Object> dataModel,String templateName){
  try {
   this.getTemplate(templateName).process(dataModel, new PrintWriter(System.out));
  } catch (TemplateException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 /**
  *
  * @param dataModel 数据模型
  * @param templateName 输出模版
  * @param filePath  输出文件路径
  */
 public void fprint(Map<String, Object> dataModel,String templateName,String filePath){
  try {
   this.getTemplate(templateName).process(dataModel, new FileWriter(new File(filePath)));
  } catch (TemplateException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值