zoukankan      html  css  js  c++  java
  • freemarker 用template快速构造XML

    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>
    参考网站如下:
  • 相关阅读:
    什么是高大上项目?
    spring事务回滚问题
    分布式ActiveMQ集群
    基于bootstarp的Dailog
    js实现的笛卡尔乘积-商品发布
    MemcachedClient 使用说明
    docker centos容器无法yum
    java Graphics2D 画图
    spring boot 访问外部http请求
    JSON 数据重复 出现$ref
  • 原文地址:https://www.cnblogs.com/xue88ming/p/7182998.html
Copyright © 2011-2022 走看看