package org.fh.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class Freemarker {
public static void print(String ftlName, Map<String,Object> root, String ftlPath) throws Exception{
try {
Template temp = getTemplate(ftlName, ftlPath);
temp.process(root, new PrintWriter(System.out));
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void printFile(String ftlName, Map<String,Object> root, String outFile, String filePath, String ftlPath) throws Exception{
try {
File file = new File(PathUtil.getProjectpath() + filePath + outFile);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
Template template = getTemplate(ftlName, ftlPath);
template.process(root, out);
out.flush();
out.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Template getTemplate(String ftlName, String ftlPath) throws Exception{
try {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setEncoding(Locale.CHINA, "utf-8");
cfg.setDirectoryForTemplateLoading(new File(PathUtil.getProjectpath()+"/admin/template/ftl/"+ftlPath));
Template temp = cfg.getTemplate(ftlName);
return temp;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結