package com.dji.sample.patches.xml.utils;
|
|
import com.dji.sample.patches.xml.mode.XMLTemplateModel;
|
import freemarker.template.Configuration;
|
import freemarker.template.Template;
|
import lombok.extern.slf4j.Slf4j;
|
|
import java.io.*;
|
import java.nio.charset.StandardCharsets;
|
|
/**
|
* @PROJECT_NAME: drone
|
* @DESCRIPTION:
|
* @USER: aix
|
* @DATE: 2024/4/3 9:58
|
*/
|
@Slf4j
|
public class CreateWaylineFileUtils {
|
|
/**
|
* 生成航线文件
|
* @param xmlModel
|
*/
|
public static void createWaylineFile(XMLTemplateModel xmlModel,String templeFilePath,String targetTempleFilePath,String waylineFilePath,String targetWaylineFilePath) {
|
|
// xml2XmlDoc(xmlModel, "home\\drone\\server\\template\\template.xml", "home\\drone\\server\\template\\wpmz\\template.kml");
|
// xml2XmlDoc(xmlModel, "home\\drone\\server\\template\\waylines.xml", "home\\drone\\server\\template\\wpmz\\waylines.wpml");
|
|
xml2XmlDoc(xmlModel, templeFilePath, targetTempleFilePath);
|
xml2XmlDoc(xmlModel, waylineFilePath, targetWaylineFilePath);
|
}
|
|
/**
|
* 将xml模板转换为newxml
|
*
|
* @param model 需要填充到模板的数据
|
* @param templetFilePath 模板文件路径
|
* @param targetFilePath 目标文件保存路径
|
*/
|
private static void xml2XmlDoc(XMLTemplateModel model, String templetFilePath, String targetFilePath) {
|
Writer out = null;
|
try {
|
// 将模板文件路径拆分为文件夹路径和文件名称
|
String ge = "/";
|
if (templetFilePath.indexOf("\\") >= 0) {
|
ge = "\\";
|
}
|
String tempLetDir = templetFilePath.substring(0, templetFilePath.lastIndexOf(ge));
|
// 注意:templetFilePath.lastIndexOf("/")中,有的文件分隔符为:\ 要注意文件路径的分隔符
|
String templetName = templetFilePath.substring(templetFilePath.lastIndexOf(ge) + 1);
|
// 将目标文件保存路径拆分为文件夹路径和文件名称
|
String targetDir = targetFilePath.substring(0, targetFilePath.lastIndexOf(ge));
|
String targetName = targetFilePath.substring(targetFilePath.lastIndexOf(ge) + 1);
|
Configuration configuration = new Configuration();
|
configuration.setDefaultEncoding(String.valueOf(StandardCharsets.UTF_8));
|
// 如果目标文件目录不存在创建
|
File file = new File(targetDir);
|
if (!file.exists()) {
|
file.mkdirs();
|
}
|
//加载模板数据(从文件路径中获取文件)
|
configuration.setDirectoryForTemplateLoading(new File(tempLetDir));
|
//获取模板实例
|
Template template = configuration.getTemplate(templetName);
|
File outFile = new File(targetDir + File.separator + targetName);
|
//模板和数据模型合并生成文件
|
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8));
|
//生成文件
|
template.process(model, out);
|
out.flush();
|
out.close();
|
} catch (Exception e) {
|
log.error("write xml failed:", e);
|
} finally {
|
if (out != null) {
|
try {
|
out.close();
|
} catch (IOException e) {
|
log.error("close out failed:", e);
|
}
|
}
|
}
|
}
|
|
}
|