spring boot 打jar包,獲取resource路徑下的檔案
阿新 • • 發佈:2018-11-07
前言:最近在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);
File newFile = new File(newFilePath + ftlName); if (newFile.isFile() && newFile.exists()) { return newFilePath; } 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; }
}