工具类
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");
}