freemarker解析模板文件

<div class="iteye-blog-content-contain" style="font-size: 14px"></div>

<pre>

// templatePath模板文件存放路径
// templateName 模板文件名称
// filename 生成的文件名称
public static void analysisTemplate(String templatePath, String templateName, String fileName, Map<?, ?> root) {
try {
Configuration config = new Configuration();
// 设置要解析的模板所在的目录,并加载模板文件
config.setDirectoryForTemplateLoading(new File(templatePath));
// 设置包装器,并将对象包装为数据模型
config.setClassicCompatible(true);
config.setObjectWrapper(new BeansWrapper());
config.setNumberFormat("0.##");

config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
// config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
// config.setTemplateUpdateDelay(0);
// config.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");

// 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
// 否则会出现乱码
Template template = config.getTemplate(templateName, "UTF-8");
// 合并数据模型与模板
FileOutputStream fos = new FileOutputStream(fileName);
Writer out = new OutputStreamWriter(fos, "UTF-8");
template.process(root, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
</pre>

猜你喜欢

转载自1282084618.iteye.com/blog/2319926