?? freemarker.java~14~
字號(hào):
package com.ksgl.system.yolo;import java.io.*;import java.util.HashMap;import java.util.Map;import freemarker.template.*;/** * 測(cè)試FreeMarker. * * @author Terry.Chan * */public class FreeMarker { private Configuration freemarker_cfg = null; static String sGeneFilePath = "d:\\test\\"; static String sGeneFileName = "freemarker.htm"; static String sTempPlateFilePath = "d:\\test\\"; public static void main(String[] args) throws IOException { // @todo 創(chuàng)建一個(gè)類,然后創(chuàng)建instance NewsItem aItem = new NewsItem(); aItem.loadData(); FreeMarker test = new FreeMarker(); Map root = new HashMap(); root.put("newsitem", aItem); boolean bOK = test.geneHtmlFile("template.ftl", root, sGeneFilePath, sGeneFileName); } /** * 獲取freemarker的配置. freemarker本身支持classpath,目錄和從ServletContext獲取. */ public Configuration getFreeMarkerCFG() { if (null == freemarker_cfg) { // Initialize the FreeMarker configuration; // - Create a configuration instance freemarker_cfg = new Configuration(); // - FreeMarker支持多種模板裝載方式,可以查看API文檔,都很簡(jiǎn)單:路徑,根據(jù)Servlet上下文,classpath等等 // htmlskin是放在classpath下的一個(gè)目錄 // freemarker_cfg.setClassForTemplateLoading(this.getClass(), // “/htmlskin”); // freemarker_cfg.setTemplateLoader(arg0) // freemarker_cfg.set try { freemarker_cfg.setDirectoryForTemplateLoading(new File( sTempPlateFilePath)); } catch (Exception ex) { ex.printStackTrace(); } } return freemarker_cfg; } /** * 生成靜態(tài)文件. * * @param templateFileName * 模板文件名,相對(duì)htmlskin路徑,例如”/tpxw/view.ftl” * @param propMap * 用于處理模板的屬性O(shè)bject映射 * @param htmlFilePath * 要生成的靜態(tài)文件的路徑,相對(duì)設(shè)置中的根路徑,例如 “/tpxw/1/2005/4/” * @param htmlFileName * 要生成的文件名,例如 “1.htm” */ public boolean geneHtmlFile(String templateFileName, Map propMap, String htmlFilePath, String htmlFileName) { // @todo 從配置中取得要靜態(tài)文件存放的根路徑:需要改為自己的屬性類調(diào)用 try { Template t = getFreeMarkerCFG().getTemplate(templateFileName); // 如果根路徑存在,則遞歸創(chuàng)建子目錄 creatDirs(htmlFilePath); File afile = new File(htmlFilePath + "/" + htmlFileName); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(afile))); t.process(propMap, out); } catch (TemplateException e) { System.out.println("freemarkertest.java error@@@@@@"+e); return false; } catch (IOException e) { System.out.println("freemarkertest.java error@@@@@@"+e); return false; } return true; } /** * 創(chuàng)建多級(jí)目錄 * * @param aParentDir * String * @param aSubDir * 以 / 開頭 * @return boolean 是否成功 */ public static boolean creatDirs(String path) { File aFile = new File(path); if (!aFile.exists()) { return aFile.mkdirs(); } else { return true; } }}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -