美文网首页
freeMarker输入文件输出文件改成输入String输出St

freeMarker输入文件输出文件改成输入String输出St

作者: 不知不怪 | 来源:发表于2020-12-23 15:37 被阅读0次

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());

    }

}

相关文章

网友评论

      本文标题:freeMarker输入文件输出文件改成输入String输出St

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