標籤:freemarker html
freemarker將檔案讀寫到HTML中
1、設計思路
(1)寫freemarker模板方法
(2)寫測試檔案方法
(3)建立ftl檔案
(4)在指定的路徑下,建立檔案夾
2、寫freemarker模板方法
/** * 輸出檔案到指定的路徑下 * @Title:printFile * @Description: * @param:@param name * @param:@param root * @param:@param outputFile * @return: void * @throws */ public void printFile(String name,Map<String,Object> root,String outputFile) { FileWriter out = null; try { //寫入到指定的檔案路徑 out = new FileWriter(new File("D:\\MyEclipse\\Maven\\ftl\\" + outputFile)); Template temp = this.getTemplate(name); try { temp.process(root, out); } catch (TemplateException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } finally { if(out != null) try {//關閉檔案流out.close(); } catch (IOException e) {e.printStackTrace(); } } }
3、寫測試檔案方法
/** * * @Title:testFreemarkerFile * @Description: * @param: * @return: void * @throws */@Testpublic void testFreemarkerFile(){//建立資料模型Map<String,Object> root = new HashMap<String,Object>();//為資料模型添加值root.put("username", "張三");root.put("age", "22");root.put("sex", "男");//將資料模型和模板中的資料輸出到控制台ft.printFile("user.ftl", root,"user.html");}
4、建立ftl檔案
姓名:${username}年齡:${age}性別:${sex}
5、建立檔案夾
D:\MyEclipse\Maven\ftl
6、產生結果
(1)產生user.html
(2)控制台產生的結果
姓名:張三年齡:22性別:男