欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

FreeMarker 解析后缀名文件

程序员文章站 2022-03-15 17:09:01
...

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 它都可以解析的

 

相关标签: freemarker