依赖
<!-- FreeMarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
工具类:FreemarkerUtil.java
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
/**
* @description FreeMarker代码生成工具类
*/
public class FreemarkerUtil {
/**
* 根据模板,利用提供的数据,生成文件
*
* @param ftlNameWithPath 模板文件路径
* @param data 数据
* @param aimFileName 最终生成的文件路径
* @throws IOException
* @throws TemplateException
*/
public static void execute(String ftlNameWithPath, Map<String, Object> data, String aimFileName) throws IOException, TemplateException {
//创建Freemarker配置实例
Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
int i = ftlNameWithPath.lastIndexOf("/") == -1 ? ftlNameWithPath.lastIndexOf("\\") : ftlNameWithPath.lastIndexOf("/");
cfg.setDirectoryForTemplateLoading(new File(ftlNameWithPath.substring(0, i + 1)));
cfg.setDefaultEncoding("UTF-8");
//加载模板文件
Template t1 = cfg.getTemplate(ftlNameWithPath.substring(i + 1));
Writer out = new FileWriter(new File(aimFileName));
t1.process(data, out);
out.flush();
out.close();
}
}
测试模板:index.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>${titleName}的主页</title>
</head>
<body>
<h3>欢迎访问${userName}的主页</h3>
${msg}
</body>
</html>
代码生成:CodeGenerator.java
import freemarker.template.TemplateException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @description 代码生成
*/
public class CodeGenerator {
public static void main(String[] args) throws TemplateException, IOException {
Map<String, Object> map = new HashMap<>();
map.put("titleName", "JngKang");
map.put("userName", "JngKang");
map.put("msg", "JngKang的主页");
// 模板文件路径
String ftlNameWithPath = "D:\\Code\\Study\\CodeTestDemo\\src\\main\\java\\test\\index.ftl";
// 生成文件路径
String aimFileName = "JngKangIndex.html";
FreemarkerUtil.execute(ftlNameWithPath, map, aimFileName);
}
}
生成结果:index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JngKang的主页</title>
</head>
<body>
<h3>欢迎访问JngKang的主页</h3>
JngKang的主页
</body>
</html>