public class ExportToXmlUtil {
private Configuration configuration = null;
public ExportToXmlUtil(){
configuration = new Configuration();
// configuration.setDefaultEncoding("UTF-8");
}
public static void main(String[] args) {
ExportToXmlUtil test = new ExportToXmlUtil();
test.createContextXml();
}
public void createContextXml(){
Map<String,String> dataMap=new HashMap<>();
getData(dataMap);
configuration.setClassForTemplateLoading(this.getClass(), "classpath:/template"); //FTL文件所存在的位置,放在与java相同的包下
Template t=null;
try {
t = configuration.getTemplate("contextxml.ftl"); //文件名
} catch (IOException e) {
e.printStackTrace();
}
File outFile = new File("D:/forK8sOutFile/context.xml"); //生成文件的路径
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//这里赋值的时候需要注意,xml中需要的数据你必须提供给它,不然会报找不到某元素错的.
private Map<String,String> getData(Map<String, String> dataMap) {
dataMap.put("name", "testName");
dataMap.put("auth", "testAuth");
return dataMap;
}
}
我的项目结构图随后附上