前言:最近在spring boot項目靜態類中獲取resource路徑下文件,在idea中啟動都可以獲取,但是打包后變成了jar包 就無法獲取到。
我想到了兩種方法,一種是根據http訪問靜態資源比如:localhost:9080/static/template/xxx.ftl文件。
另外一種是根據流獲取到文件,然后拷貝到新的文件夾下面。下面說的就是第二種方式的代碼
public class DocUtil {
//此路徑是其他方法進行調用,且只需要加載一次
private static String sourceTemplatePath;
// 模板文件名稱 位於 resource/static/template下面 private static String[] ftlArray = {"申請書.ftl", "授權委托書.ftl", "法定代表人身份證明書.ftl", "逾期督促申請.xls"}; static { //靜態方法調用一次 sourceTemplatePath = createFtlFileByFtlArray(); } private static String createFtlFileByFtlArray() { String ftlPath = "static/template/"; String path = ""; for (int i = 0; i < ftlArray.length; i++) { path = createFtlFile(ftlPath, ftlArray[i]); if (null == path) { logger.info("ftl not copy success:" + ftlArray[i]); } } return path; } private static String createFtlFile(String ftlPath, String ftlName) { try {
//獲取當前項目所在的絕對路徑 String proFilePath = System.getProperty("user.dir"); logger.info("project run path:" + proFilePath); //獲取模板下的路徑
String newFilePath = proFilePath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + ftlPath;
newFilePath = newFilePath.replace("/", File.separator);
logger.info("newFilePath:" + newFilePath);
//檢查項目運行時的src下的對應路徑
File newFile = new File(newFilePath + ftlName);
if (newFile.isFile() && newFile.exists()) {
return newFilePath;
}
//當項目打成jar包會運行下面的代碼,並且復制一份到src路徑下(具體結構看下面圖片)
InputStream certStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(ftlPath + ftlName);
byte[] certData = IOUtils.toByteArray(certStream);
FileUtils.writeByteArrayToFile(newFile, certData); return newFilePath; } catch (IOException e) { logger.error("復制ftl文件失敗--> 異常信息:" + e); } return null; }
}
項目打成jar包時的文件路徑結構