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>
参考网站如下: