package com.r.util;
import java.io.*;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import freemarker.template.*;
public class MakeHtmlFile {
private final Log logger = LogFactory.getLog(getClass());
private Configuration freemarkerCfg = null;
private String templatePath = "";
private String realBuildPath = "";
/**
*
* @param realBuildPath根目錄絕對路徑
* @param templatePath模板相對路徑,不包含模板名稱
*/
public MakeHtmlFile(String realBuildPath, String templatePath) {
this.templatePath = templatePath;
this.realBuildPath = realBuildPath;
setTemplatePath();
}
/**
*
* @param templatePath:模板絕對路徑
*/
private void setTemplatePath() {
// 設置freemarker的參數
freemarkerCfg = new Configuration();
try {
File file = new File(realBuildPath+templatePath);
freemarkerCfg
.setDirectoryForTemplateLoading(file);
freemarkerCfg.setObjectWrapper(new DefaultObjectWrapper());
freemarkerCfg.setDefaultEncoding("UTF-8");
} catch (IOException ex) {
System.out.println("No Directory found,please check you config."n"
+ realBuildPath+templatePath);
}
}
/**
* 生成靜態文件
*
* @param templateFileName
* 模版名稱eg:(biz/order.ftl)
* @param propMap
* 用于處理模板的屬性Object映射
* @param htmlFilePath
* 要生成的靜態文件的路徑,相對設置中的根路徑,例如 "/biz/2006/5/"
* @param htmlFileName
* 要生成的文件名,例如 "123.htm"
* @return
*/
public boolean buildHtml(String templateFileName, Map propMap,
String htmlFilePath, String htmlFileName) {
try {
Template template = freemarkerCfg.getTemplate(templateFileName);
template.setEncoding("UTF-8");
// 創建生成文件目錄
creatDirs(realBuildPath, htmlFilePath);
File htmlFile = new File(realBuildPath + htmlFilePath
+ htmlFileName);
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(htmlFile), "UTF-8"));
template.process(propMap, out);
out.flush();
return true;
} catch (TemplateException ex) {
ex.printStackTrace();
logger.error("Build Error" + templateFileName, ex);
return false;
} catch (IOException e) {
logger.error("Build Error" + templateFileName, e);
return false;
}
}
/**
* 創建多級目錄
*
* @param aParentDir
* String
* @param aSubDir
* 以 / 開頭
* @return boolean 是否成功
*/
public static boolean creatDirs(String aParentDir, String aSubDir) {
File aFile = new File(aParentDir);
if (aFile.exists()) {
File aSubFile = new File(aParentDir + aSubDir);
if (!aSubFile.exists()) {
return aSubFile.mkdirs();
} else {
return true;
}
} else {
return false;
}
}
}
別著急,等我學會了,我一步步說明一什么意思,