All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.yes.tools.generator.utils.TemplateUtils Maven / Gradle / Ivy

There is a newer version: 2.0.4
Show newest version
package org.yes.tools.generator.utils;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * @author Co.
 * @date 2022年 10月15日 16:51:24
 */
public class TemplateUtils {

    /***
     * 获取模板·
     *
     * @author Co.
     * @date: 2022/10/15 15:28
     * @return
     */
    public static Template getTemplate(String filePath) throws IOException {
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("utf-8");
        System.out.println("getResourceAsStream------> templates/" + filePath);
        //获取文件内容
        InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("templates/" + filePath);
        String content = new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8))
                .lines()
                .collect(Collectors.joining("\n"));

        //将其填充到stringTemplateLoader中
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        stringTemplateLoader.putTemplate(filePath, content);
        configuration.setTemplateLoader(stringTemplateLoader);

        return configuration.getTemplate(filePath);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy