您的位置:首页 > 编程语言 > Java开发

freemarker 用template快速构造XML

2016-05-02 22:58 531 查看
freemarker 用template快速构造XML

1. 需要jar  freemarker-2.3.8.jar
2. demo 如下:
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class Test {
/**
* <一句话功能简述>
* <功能详细描述>
* @param map map
* @param fileName fileName
* @return 字符串流
* @see [类、类#方法、类#成员]
*/
@SuppressWarnings("unchecked")
public static String buil(Map map, String fileName)
{
String url = Test.class.getResource("").getPath().replaceAll("%20", " ");
String path = url;
StringWriter out = new StringWriter();
try
{
Configuration configuration = new Configuration();
configuration.setDirectoryForTemplateLoading(new File(path));

Template template = configuration.getTemplate(fileName);
template.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
template.setEncoding("UTF-8");
template.setOutputEncoding("UTF-8");
Environment env = template.createProcessingEnvironment(map, out);

env.process();
out.flush();
}
catch (Exception e)
{

}
finally
{
try
{
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}

return out.toString();
}
public static void main(String[]arrgs)
{
Map<String,String> map= new HashMap<String,String>();
map.put("id", "test123456");
System.out.println(buil(map,"test.ftl"));
}
}


test.ftl
<xml id ="${id}">
</xml>
参考网站如下:
http://freemarker.org/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  freemarker web java