Recently, the files under the resource path are obtained in the static class of the spring boot project, which can be obtained when starting in the idea, but can't be obtained when the package becomes a jar package. I came up with two methods. One is to access static resources based on http, such as
localhost:9080/static/template/xxx.ftl file. The other is to get the file according to the stream, and then copy it to a new folder. Here's the code for the second way
public class DocUtil {
//This path is called by another method and only needs to be loaded onceprivate static String sourceTemplatePath;
// The template file name is under resource/static/template private static String[] ftlArray = {"Application.ftl", "Power of attorney.ftl", "Identity certificate of legal representative.ftl", "Overdue application.xls"}; static { //Static method call once 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 {
//Get the absolute path of the current project String proFilePath = System.getProperty("user.dir"); logger.info("project run path: " + proFilePath); //Get the path under the templateString 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("copy ftl File Failure--> Exception information:" + e); } return null; }
}