模板文件hello.ftl
<html> <head> <title>demo</title> </head> <body> hello ${name} </body> </html>
pom.xml加入freemarker的依赖
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.16</version> </dependency>
Java代码
package cn.code; import freemarker.template.Configuration; import freemarker.template.Template; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; public class Generator { public static void main(String[] args) throws Exception{ //创建Configuration对象 Configuration configuration = new Configuration(); //设置模板所在目录,我放到了classpath String path = Generator.class.getClassLoader().getResource("").getPath(); configuration.setDirectoryForTemplateLoading(new File(path)); //获取模板 Template template = configuration.getTemplate("hello.ftl"); //设置数据并执行 Map map = new HashMap(); map.put("name", "fengqing"); Writer writer = new OutputStreamWriter(new FileOutputStream("G:/hello.html")); template.process(map, writer); } }