freemark工具类简单使用
FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。
它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
所需要的pom依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
工具类代码:
package com.common.base.utils;
import java.io.*;
import java.util.Locale;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
* @Auther: tony_t_peng
* @Date: 2020-12-08 11:25
* @Description:
*/
public class FreeMarkerUtil {
/**
** @param fileName 要读取的文件名,包括文件后缀名
* * @param item 传入的map
* * @param filePath 要读取的文件路径
*/
public static String generateString(String fileName, String templatePath, Map<String, Object> data) throws IOException {
StringWriter out = new StringWriter();
process(fileName,templatePath,data,out);
return out.getBuffer().toString();
}
public static void generateFile(String fileName, String templatePath, Map<String, Object> data,File outFile) throws IOException {
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
process(fileName,templatePath,data,out);
}
private static void process(String fileName, String templatePath,Map<String, Object> data, Writer out) throws IOException {
try {
// 通过Template可以将模板文件输出到相应的流
Template template = getTemplate(fileName, templatePath);
template.process(data, out);
out.flush();
} catch (Exception e){
e.printStackTrace();
}finally {
if(out!=null){
out.close();
}
}
}
private static Template getTemplate(String fileName, String templatePath){
try {
// 通过Freemaker的Configuration读取相应的ftl
Configuration cfg = new Configuration();
cfg.setEncoding(Locale.CHINA, "utf-8");
// 设定去哪里读取相应的ftl模板文件
cfg.setDirectoryForTemplateLoading(new File(templatePath));
// 在模板文件目录中找到名称为name的文件
Template temp = cfg.getTemplate(fileName);
return temp;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
单元测试代码:
String IDPS_TEMPLATE_NAME="CN.D.MANULIFE.TEMPLATE.ftl"; //模板文件名
String filePath = getClass().getResource("/tempalte/freemark/").getPath(); //模板文件夹地址
File file = new File(OUT_FILE_PATH+"CN.D.MANULIFE.DBSCOVR.txt"); //输出文件对象
FreeMarkerUtil.generateFile(IDPS_TEMPLATE_NAME,filePath,buildCoverageData(asOfDt),file);//buildCoverageData封装要给map,用以存放对象
ftl 模板代码 示例:
${header!""}
<#list items as item>
${item.field1!""}${item.field2!""}
</#list>
${trailer!""}
${item.field1!""}是非空判断,如果没有非空判断,null的情况下会报错
浙公网安备 33010602011771号