Freemarker的简单使用
package com.paic.util;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
public class FreemarkerUtil {
public Template getTemplate(String name){
Template template=null;
try {
public Template getTemplate(String name){
Template template=null;
try {
//通过Freemarker的Configration读取相应的ftl;
Configuration cfg=new Configuration();
//去哪里读取相应的ftl模板
File file = new File("src/template") ;
cfg.setDirectoryForTemplateLoading(file);
//在莫办文件中寻找名字为name的模板
template= cfg.getTemplate(name);
} catch (IOException e) {
e.printStackTrace();
}
return template;
}
public void print(String name,Map<String,Object> rootMap){
try {
Template template = this.getTemplate(name);
template.process(rootMap,new PrintWriter(System.out));
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void fprint(String name,Map<String,Object> rootMap,String outFile){
FileWriter out=null;
try {
out =new FileWriter(new File("G:\\freemarker\\"+outFile));
Template template = this.getTemplate(name);
template.process(rootMap,out);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}finally {
if (null!=out){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Configuration cfg=new Configuration();
//去哪里读取相应的ftl模板
File file = new File("src/template") ;
cfg.setDirectoryForTemplateLoading(file);
//在莫办文件中寻找名字为name的模板
template= cfg.getTemplate(name);
} catch (IOException e) {
e.printStackTrace();
}
return template;
}
public void print(String name,Map<String,Object> rootMap){
try {
Template template = this.getTemplate(name);
template.process(rootMap,new PrintWriter(System.out));
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void fprint(String name,Map<String,Object> rootMap,String outFile){
FileWriter out=null;
try {
out =new FileWriter(new File("G:\\freemarker\\"+outFile));
Template template = this.getTemplate(name);
template.process(rootMap,out);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}finally {
if (null!=out){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}