同时支持idea调试和jar包运行
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class DocUtil {
//此路径是其余方法进行调用,且只需要加载一次
private static String sourceTemplatePath;
// 读取文件名称
// private static String[] ftlArray = {"shopPDF.ftl","yahei.ttf"};
private static String[] ftlArray = {"krb5.conf", "user.keytab"};
// resources下模板文件夹名称
// private static String temPath = "templates/shopsummary/";
private static String temPath = "";
//模块名,针对多模块项目。单模块项目需删除
// private static String modelPath = String.format("jeecg-module-system%sjeecg-system-biz", File.separator);
static {
//静态方法调用一次
sourceTemplatePath = createFtlFileByFtlArray();
}
// 获取临时文件路径
public static String getSourceTemplatePath() {
return sourceTemplatePath;
}
//获取临时文件模板路径
public static String getRentalAgreementPath() {
return sourceTemplatePath + ftlArray[0];
}
private static String createFtlFileByFtlArray() {
String path = "";
for (int i = 0; i < ftlArray.length; i++) {
path = createFtlFile(temPath, ftlArray[i]);
if (null == path) {
log.info("not copy success:" + ftlArray[i]);
}
}
return path;
}
private static String createFtlFile(String ftlPath, String ftlName) {
try {
//获取当前项目所在的绝对路径
String proFilePath = System.getProperty("user.dir");
log.info("project run path:" + proFilePath);
//本地调试运行
ClassPathResource resource = new ClassPathResource("krb5.conf");
if (resource != null && resource.getURI() != null && resource.getURI().getPath() != null) {
String localFilePath = resource.getURI().getPath().replace("krb5.conf", "");
log.info("localFilePath:" + localFilePath);
return localFilePath;
}
//jar包运行
String newFilePath = proFilePath + File.separator + "conf" + File.separator + ftlPath;
newFilePath = newFilePath.replace("/", File.separator);
log.info("newFilePath:" + newFilePath);
File newFile = new File(newFilePath + ftlName);
//当项目打成jar包会运行下面的代码,而且复制一份到conf路径下
InputStream certStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(ftlPath + ftlName);
byte[] certData = IOUtils.toByteArray(certStream);
FileUtils.writeByteArrayToFile(newFile, certData);
return newFilePath;
} catch (IOException e) {
log.error("复制文件失败--> 异常信息:" + e);
}
return "";
}
}
使用:
String KRB5_FILE = DocUtil.getSourceTemplatePath() + "krb5.conf";
jar包运行时,会在jar同级目录下新建conf文件夹,并生成配置文件