标签:
例子:MakeFileManager.java
package example;
import freemarker.template.Configuration;
import java.text.SimpleDateFormat;
import java.io.File;
import freemarker.template.DefaultObjectWrapper;
import java.util.Map;
import java.util.HashMap;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import freemarker.template.TemplateException;
import java.io.IOException;
import freemarker.template.Template;
public class MakeFileManager {
public String make(Book book, BookFtl bookFtl) {
Configuration cfg = new Configuration();//配制
String realPath = bookFtl.getRealPath();
String templatePath = realPath + "/WEB-INF/templates/book";
String cDateStr = "book/" +
new SimpleDateFormat("yyyyMMdd").format(new java.util.
Date());
String filePostfix = ".html";
String path = realPath + "/" + cDateStr;
String fileTimeName = new SimpleDateFormat("yyyyMMddhhmmss").format(new
java.util.Date());
String returnFileName = cDateStr + "/" + fileTimeName + filePostfix;
String fileName = "";
File bookDir = new File(path);
if (bookDir.exists()) {
fileName = path + "/" + fileTimeName + filePostfix;
} else {
bookDir.mkdirs();
fileName = path + "/" + fileTimeName + filePostfix;
}
try {
//设置freemarker的参数
cfg.setNumberFormat("0.##########");//生成html文件时web.xml配制无效
//cfg.setEncoding();
cfg.setDirectoryForTemplateLoading(new File(templatePath));
cfg.setObjectWrapper(new DefaultObjectWrapper());
Template bookTemplate = cfg.getTemplate(bookFtl.getTemplateName());//模板对象
Map root = new HashMap();
root.put("book", book);
root.put("book2",book);
Writer out = new OutputStreamWriter(new FileOutputStream(fileName));
try {
bookTemplate.process(root, out);
} catch (TemplateException e) {
e.printStackTrace();
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
return returnFileName;
}
}
标签:
原文地址:http://www.cnblogs.com/Crow00/p/4712984.html