一、准备工作
- 引入基础的springboot环境
- 引入freemark依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
- 创建json模版
{
"parameter":{
"username":"${readerUsername}",
"password":"${readerPassword}"
}
}
二、创建读取模版工具类
package com.luwang.data.datax.util;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.StringWriter;
import java.util.HashMap;
public class FreeMarkerTemplateUtils {
public String getData(String filePath, HashMap<Object, Object> map) throws Exception {
StringWriter writer = new StringWriter();
//创建配置类
Configuration cfg = new Configuration(Configuration.getVersion());
// 设置类加载机制加载模板,这里可以参考http://freemarker.foofun.cn/pgui_config_templateloading.html的内容,这是用的第二种方法。
cfg.setClassForTemplateLoading(this.getClass(),"/");
// 设置字符集
cfg.setDefaultEncoding("UTF-8");
// 加载模板
Template template = cfg.getTemplate(filePath);
// 静态化内容
template.process(map,writer);
String content = writer.toString();
return content;
}
}
三、根据模版生成Json文件
@Test
void myDeliver3() throws Exception {
// 该文件在resources目录下
String filePath = "/job/JobModel.ftl";
FreeMarkerTemplateUtils utils = new FreeMarkerTemplateUtils();
HashMap<Object, Object> map = new HashMap<Object, Object>();
map.put("readerUsername","root");
map.put("readerPassword","Lqgs@2022");
map.put("writeUsername","Lqgs@2022");
map.put("writePassword","Lqgs@2022");
map.put("channel","2");
String content = utils.getData(filePath,map);
System.out.println(content);
FileWriter fileWriter = new FileWriter("D:\\JavaCode\\data-middle-platform\\data-datax\\datax\\job\\JobModel-2023-01.json");
fileWriter.write(content);
fileWriter.close();
}
标签:Map,Java,String,map,content,Json,put,new
From: https://www.cnblogs.com/zouxiaoao/p/17781851.html