Utils-FreeMarker 工具類

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);
    	}

     

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章