-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTemplateUtil.java
76 lines (71 loc) · 2.63 KB
/
TemplateUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package cn.xanderye.util;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
/**
* 模板工具类
* @author XanderYe
* @date 2021/2/9 17:29
*/
public class TemplateUtil {
/**
* 从resources下获取ftl模板导出文件
* @param root
* @param dictName
* @param ftlName
* @param targetPath
* @param targetName
* @return void
* @author XanderYe
* @date 2021/2/9
*/
public static void generateFromResources(Map<String, Object> root, String dictName, String ftlName, String targetPath, String targetName) throws IOException, TemplateException {
File parentFile = new File(targetPath);
if (!parentFile.exists()) {
parentFile.mkdirs();
}
try (FileWriter fw = new FileWriter(new File(targetPath + "/" + targetName));
BufferedWriter bw = new BufferedWriter(fw)) {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
cfg.setDefaultEncoding("UTF-8");
cfg.setClassForTemplateLoading(TemplateUtil.class, "/" + dictName);
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_28));
Template temp = cfg.getTemplate(ftlName, "UTF-8");
temp.process(root, bw);
bw.flush();
}
}
/**
* 从文件获取ftl模板导出文件
* @param root
* @param sourcePath
* @param ftlName
* @param targetPath
* @param targetName
* @return void
* @author XanderYe
* @date 2021/2/9
*/
public static void generateFromFile(Map<String, Object> root, String sourcePath, String ftlName, String targetPath, String targetName) throws IOException, TemplateException {
File parentFile = new File(targetPath);
if (!parentFile.exists()) {
parentFile.mkdirs();
}
try (FileWriter fw = new FileWriter(new File(targetPath + "/" + targetName));
BufferedWriter bw = new BufferedWriter(fw)) {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
cfg.setDefaultEncoding("UTF-8");
cfg.setDirectoryForTemplateLoading(new File(sourcePath));
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_28));
Template temp = cfg.getTemplate(ftlName, "UTF-8");
temp.process(root, bw);
bw.flush();
}
}
}