美文网首页
freemarker输出到文本string

freemarker输出到文本string

作者: 不知不怪 | 来源:发表于2021-03-14 00:36 被阅读0次
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());

    }

}

相关文章

网友评论

      本文标题:freemarker输出到文本string

      本文链接:https://www.haomeiwen.com/subject/anwfcltx.html