您当前的位置: 首页 >  ar

【精品】超级实用的Freemarker工具类

梁云亮 发布时间:2021-08-10 20:14:28 ,浏览量:2

工具类
public class FreemarkerUtil {
    /**
     * 根据模板,利用提供的数据,生成文件
     *
     * @param sourceFile 模板文件,带路径
     * @param data       数据
     * @param aimFile    最终生成的文件,带路径
     * @throws IOException
     * @throws TemplateException
     */
    public static void execute(String sourceFile, Map data, String aimFile) throws IOException, TemplateException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);//创建Freemarker配置实例

        int i = sourceFile.lastIndexOf("/") == -1 ? sourceFile.lastIndexOf("\\") : sourceFile.lastIndexOf("/");

        cfg.setDirectoryForTemplateLoading(new File(sourceFile.substring(0, i + 1)));

        cfg.setDefaultEncoding("UTF-8");

        Template t1 = cfg.getTemplate(sourceFile.substring(i + 1));//加载模板文件
        Writer out = new FileWriter(new File(aimFile));
        t1.process(data, out);
        out.flush();
        out.close();
    }
}
测试
  • 模板文件:service.ftl

	
		${title}
	
	
		${msg}
	

  • 测试代码:
public static void main(String[] args) throws TemplateException, IOException {//DBUtils中的事务
    Map map = new HashMap();
    map.put("title", "首页");
    map.put("msg", "好好学习,天天向上!");
    FreemarkerUtil.execute("E:/credits/src/main/resources/ftl/demo.ftl", map, "haha.html");
}
关注
打赏
1688896170
查看更多评论

梁云亮

暂无认证

  • 2浏览

    0关注

    1176博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.5025s