? 相信很多人都用過freemarker,或做視圖,或模板,或生成靜態文件等,但是有多少人做過這樣的應用,通過模板后,不是要輸出靜態的內容,而是直接在代碼中獲取處理模板后的內容,研究了下API,freemarker里提供StringWriter,StringWriter不需要指定文件,所以看名字也能知道,他能直接獲取處理后的內容,代碼如下?
- import?java.io.IOException;??
- import?java.io.StringWriter;??
- import?java.util.ArrayList;??
- import?java.util.HashMap;??
- import?java.util.List;??
- import?java.util.Map;??
- ??
- import?freemarker.template.Configuration;??
- import?freemarker.template.Template;??
- import?freemarker.template.TemplateException; ?
- ??
- public?class?TestFreemarker??
- {??
- ??????
- ????@SuppressWarnings("unchecked")??
- ????public?static?void?main(String[]?args)?throws?IOException??
- ????{??
- ????????Configuration?cfg?=?new?Configuration();?
- cfg.setDirectoryForTemplateLoading(new File("E:\\kuaipan\\workspace2016\\freemarker001\\src\\hello"));?
- ????????List<String>?strList=new?ArrayList<String>();??
- ????????for?(int?i?=?0;?i?<?2000;?i++)??
- ????????{??
- ????????????strList.add("第??"+i+"?個");??
- ????????}??
- ??????????
- ????????Map?root?=?new?HashMap();??
- ????????root.put("message",?"您好!");??
- ????????root.put("username",?"diqiu");??
- ????????root.put("strList",?strList);??
- ????????Template?t?=?cfg.getTemplate("test.txt");??
- ??????????
- ????????//最關鍵在這里,不使用與文件相關的Writer??
- ????????StringWriter?stringWriter=new?StringWriter();??
- ??????????
- ????????try??
- ????????{??
- ????????????t.process(root,?stringWriter);??
- ??????????????
- ????????????//這里打印的就是通過模板處理后得到的字符串內容??
- ????????????System.out.println("stringWriter:?"+stringWriter.toString());??
- ????????}?catch?(TemplateException?e)??
- ????????{??
- ????????????e.printStackTrace();??
- ????????}??
- ??
- ????}??
- ??
- }??
test.txt模板里的內容如下:?
- ${message}??
- ${username}??
- ??
- ${strList?size}??
- ??
- <#list?strList?as?str>??
- ????str:${str};?哈哈??
- </#list>??