中文手册 http://freemarker.foofun.cn/index.html
英文手册 https://freemarker.apache.org/
简单使用流程:
- 制定ftl模板,放到项目文件夹,位置随意,但是需要能被调用到,语法见手册;
- 官网下载最新的freemaker.jar包,导入jar到项目中
- 创建 Configuration 实例,并初始化
Configuration config = new Configuration(Configuration.VERSION_2_3_29);
config.setDirectoryForTemplateLoading(new File("src/src-template/")); // file地址为第一步中放置模板位置
config.setDefaultEncoding("UTF-8");
// 其他设置见说明书
- 加载模板
Template tp = config.getTemplate("tp.ftl");
- 创建数据模型(即在模板中动态显示的数据)
// 使用hashmap来存储数据
Map<String, Object> root = new HashMap<>();
- 生成文件
Writer writer = new FileWriter(file); // 生成的文件
try {
tp.process(root, writer); // 模板+动态数据(root集合中包含了各种动态数据的对象)
writer.flush();
System.out.println("Written " + file.getCanonicalPath());
} finally {
writer.close();
}
更多的操作看说明。