public static void main(String[] args) throws Exception {
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("D:\\MyEclipse8.5\\freemarker\\WebRoot\\template"));
// cfg.setClassForTemplateLoading(FMParse.class, "/template");
cfg.setObjectWrapper(new DefaultObjectWrapper());
List<String> strList=new ArrayList<String>();
for (int i = 0; i < 10; i++)
{
strList.add("第 "+i+" 个");
}
Map root = new HashMap();
root.put("message", "您好!");
root.put("username", "zhangweilin");
root.put("strList", strList);
root.put("time", new Date());
String filepath="fm.flt";
Template t = cfg.getTemplate(filepath, "gbk");
//最关键在这里,不使用与文件相关的Writer
// StringWriter stringWriter=new StringWriter();
String outFile="D:\\MyEclipse8.5\\freemarker\\WebRoot\\html\\test2.html";
// Writer stringWriter= new FileWriter(new File(outFile));
Writer stringWriter=new OutputStreamWriter(new FileOutputStream(new File(outFile)), "gbk");
try
{
t.process(root, stringWriter);
//这里打印的就是通过模板处理后得到的字符串内容
System.out.println("stringWriter: "+stringWriter.toString());
} catch (TemplateException e)
{
e.printStackTrace();
}
}
注:不管你的FreeMarker模板后缀名是.ftl和.flt 它都可以解析的