示例:
import
freemarker.template.Configuration;
import
freemarker.template.SimpleHash;
import
freemarker.template.Template;
import
freemarker.template.TemplateException;
public
class
Test
...
{ public static Log log = LogFactory.getLog(Test. class ); public static void main(String[] args) ... { try ... { /**/ /* 定义中的文件内容 test.ftl ${title} ${author} ${content} */ Configuration cfg = new Configuration(); String tempDir = " d:/test " ; // 定义模板存放路径 // 根据所在地方定义路径String tempDir= URLDecoder.decode(this.getClass().getClassLoader().getResource("../").getPath(), "UTF-8"); String tempName = " test.ftl " ; // 定义模板名 String outputDir = " d:/test " ; // 定义模板输出路径 String outputName = " d:/test.txt " ; // 定义模板输出文件名 cfg.setDirectoryForTemplateLoading( new File(tempDir)); Template temp = cfg.getTemplate(tempName, Locale.US, " UTF-8 " ); SimpleHash map = new SimpleHash(); map.put( " title " , " hello " ); map.put( " author " , " beauty9235 " ); map.put( " content " , " hello,world! " ); // 定义将结果打印出来 StringWriter out = new StringWriter(); temp.process(map, out); log.debug(out.toString()); // 定义生成文件 File output = new File(outputDir, outputName); Writer writer = new FileWriter(output); try ... { temp.process(map, writer); } catch (TemplateException e) ... { e.printStackTrace(); } } catch (TemplateException t) ... { log.debug(t.getMessage()); } catch (IOException i) ... { log.debug(i.getMessage()); } } }
public void geneHtmlFile(String templateFilePath, String htmlFilePath, SimpleHash simpleHash) {
try {
Configuration cfg = new Configuration();
cfg.setDefaultEncoding("UTF-8");
cfg.setOutputEncoding("UTF-8");
cfg.setLocale(Locale.US);
cfg.setDirectoryForTemplateLoading(new File(StringUtils.substringBeforeLast(templateFilePath, "//")));
Template temp = cfg.getTemplate(StringUtils.substringAfterLast(templateFilePath, "//"));
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(htmlFilePath)), "UTF-8"));
temp.process(simpleHash,out);
} catch (IOException e) {
log.debug(e);
} catch (TemplateException e) {
log.debug(e);
}
}
public void geneHtmlFile(String templateFilePath, String htmlFilePath, Map propMap) {
try {
Configuration cfg = new Configuration();
cfg.setDefaultEncoding("UTF-8");
cfg.setOutputEncoding("UTF-8");
cfg.setLocale(Locale.US);
cfg.setDirectoryForTemplateLoading(new File(StringUtils.substringBeforeLast(templateFilePath, "//")));
Template temp = cfg.getTemplate(StringUtils.substringAfterLast(templateFilePath, "//"));
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(htmlFilePath)), "UTF-8"));
temp.process(propMap,out);
} catch (IOException e) {
log.debug(e);
} catch (TemplateException e) {
log.debug(e);
}
}