1 freeMarker默认输入,输出都是文件
2 输入,输出改成String
3 代码
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
package com.gzz.createcode;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import freemarker.cache.ByteArrayTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TestFreemarker {
public static void main(String[] args) throws TemplateException, IOException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
String content = "标题:${title}" + "内容:${content}";
final ByteArrayTemplateLoader templateLoader = new ByteArrayTemplateLoader();
templateLoader.putTemplate("test.ftlh", content.getBytes());
cfg.setTemplateLoader(templateLoader);
Template template = cfg.getTemplate("test.ftlh");
log.info("模板内空为:{}", template.toString());
Map<String, Object> map = new HashMap<>();
map.put("title", 123);
map.put("content", 456);
StringWriter stringWriter = new StringWriter();
BufferedWriter writer = new BufferedWriter(stringWriter);
template.process(map, writer);
StringReader reader = new StringReader(stringWriter.toString());
writer.flush();
writer.close();
BufferedReader r = new BufferedReader(reader);
StringBuffer sb = new StringBuffer();
String line;
while ((line = r.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
log.info("解析后:{}", sb.toString());
}
}
网友评论