Utils-FreeMarker 工具类

博客主要介绍了 FreeMarker 工具类,包含其 maven 依赖和测试代码,这些内容与信息技术领域的开发相关,可帮助开发者更好地使用 FreeMarker 进行开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FreeMarker 工具类  

  • maven 依赖 
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
package com.common.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
 * FreeMarker 工具类
 * by ChenYb date 2019/6/20
 */
public class FreeMarkerUtil {

    private final static Logger logger = LoggerFactory.getLogger(FreeMarkerUtil.class);

    /**
     * 默认模板在/src/main/resources/ 目录下
     * 默认生成的新文件在/target/static 目录下
     * fltFile flt文件名 , templatePath flt文件路径 ,fileNameOrSuffix 后缀名(前缀随机)/全名称 , datas 数据集合
     * @param fltFile
     * @param templatePath
     * @param fileNameOrSuffix
     * @param datas
     * @return 生成文件路径
     */
    public static String geneFile(String fltFile, String templatePath, String fileNameOrSuffix, Map<String, Object> datas){

        Configuration configuration = new Configuration();
        String result = null;
        try {
            String resourcePath = FreeMarkerUtil.class.getResource( "/" ).toURI().getPath();
            resourcePath = resourcePath.substring( 1 , resourcePath.indexOf( "/target" ));
            StringBuffer fltPathBuffer = new StringBuffer( resourcePath );

            if (!templatePath.contains( "/src/main/resources/" ))//默认路径在 /src/main/resources/ 下,以该路径为跟路径
                fltPathBuffer.append( "/src/main/resources/" ).append( templatePath );
            else
                fltPathBuffer.append( "/" ).append( templatePath );

            logger.info( "TEMPLATE HOME PATH : {}",fltPathBuffer );
            configuration.setDirectoryForTemplateLoading( new File( fltPathBuffer.toString() ) );
            Template temp = configuration.getTemplate(fltFile + ".ftl" );

            StringBuffer pathBuffer = new StringBuffer( resourcePath );

            //create file home
            File fileIsExists = new File( pathBuffer.append( "/target" ).append( "/static/" ).toString());
            if (!fileIsExists.exists()){
                fileIsExists.mkdir();
            }

            //检查元素
            int count = 0;
            Pattern element = Pattern.compile("\\.");
            Matcher subject = element.matcher( fileNameOrSuffix );
            while (subject.find()) {
                count++;
            }

            Random rand = new Random();
            if (count < 1)//断言名称类型
                pathBuffer.append( rand.nextInt( 10 ) ).append( "." ).append( fileNameOrSuffix );//避免文件过多
            else
                pathBuffer.append( fileNameOrSuffix );

            String path=pathBuffer.toString();
            result = path;
            logger.info( "CREATE NEW FILE PATH : {}",path );

            Writer file =  new FileWriter(new File(result));

            temp.process( datas,file);
            file.flush();
            file.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return  result;
    }
}

 测试代码

  1.  
    @Test
    	public void freemarkerTests ()throws IOException{
    		String result = FreeMarkerUtil.geneFile( "cctest", "template", "html", new HashMap<>() );
    		System.out.println(result);
    	}

     

  2. @Test
    	public void freemarkerTests ()throws IOException{
    		String result = FreeMarkerUtil.geneFile( "cctest", "/template/", "爱我中华.html", new HashMap<>() );
    		System.out.println(result);
    	}

     

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值