有时候我们需要直接转换模板字符串,而不是从数据文件读取
比如我要将${ClassName}.java直接转换结果得到我的文件名Student.java
这时,需要StringTemplateLoader来辅助,具体代码如下:
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class TestFreemarker {
public static void main(String[] args) throws Exception {
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("ClassName", "Student");
String templateContent = "${ClassName}.java";
System.out.println(parseContent(templateContent, dataMap));
}
public static String parseContent(String content, Map<String, Object> dataMap) {
try {
String tempName = StringUtils.left(content, 10);
Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
configuration.setNumberFormat("#");
StringTemplateLoader stringLoader = new StringTemplateLoader();
stringLoader.putTemplate(tempName, content);
Template template = new Template(tempName, new StringReader(content), configuration);
StringWriter stringWriter = new StringWriter();
template.process(dataMap, stringWriter);
content = stringWriter.toString();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("模板解析失败");
}
return content;
}
}
输出结果:
Student.java