Spring Boot 打包JAR 後獲取不了classpath下文件| java.io.filenotfoundexception: class path resource
May 25, 2021
在製作發送郵件的程式時,所遇到的坑
本地端運行沒問題但是打包成Jar要用docker跑image時報錯
java.io.filenotfoundexception: class path resource [static/題庫.pdf] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/docker-demo.jar!/boot-inf/classes!/static/%e9%a1%8c%e5%ba%ab.pdf at org.springframework.util.resourceutils.getfile(resourceutils.java:217) at org.springframework.core.io.abstractfileresolvingresource.getfile
因为打包後Spring會去訪問系統的路徑,但無法訪問JAR中的路徑。
必須使用resource.getInputStream()
寫入複製
ClassPathResource classPathResource = new ClassPathResource("檔案");InputStream inputStream = classPathResource.getInputStream();File somethingFile = File.createTempFile("高命中率題庫", ".pdf");//自動創建在默認的臨時文件夾中的空文件try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
}
finally {
IOUtils.closeQuietly(inputStream);
}
messageHelper.addAttachment("題庫.pdf", somethingFile);
//附件mailSender.send(mimeMessage);
讀取
ClassPathResource resource = new ClassPathResource("檔案");
InputStream inputStream = resource.getInputStream();
IOUtils.readLines(inputStream).forEach(System.out::println);
希望這篇文章能夠幫助到你(妳)
如有錯誤指正
I hope you found this guide helpful. If not, then please let me know either in the comments below, I’m Albert