我在讀取springboot下templates目錄下excel模板的時候,本地測試使用ClassPathResource都可以正常讀取,但打包成jar包傳到服務器上就無法獲取了.
報錯信息是:class path resource [xxxx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:xxxx.jar!/BOOT-INF/classes!xxxx,話不多說,先看正確的獲取方法:使用PathMatchingResourcePatternResolver。
//獲得文件流,因爲在jar文件中,不能直接通過文件資源路徑拿到文件,但是可以在jar包中拿到文件流。(一定要用流,不要嘗試去拿到絕對路徑,否則報錯!)
String txt = "";
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//Resource[] resources = resolver.getResources("templates/layout/email.html");
Resource resource = resolver.getResource("templates/layout/email.html");
Resource resource = resources[0];
//獲得文件流,因爲在jar文件中,不能直接通過文件資源路徑拿到文件,但是可以在jar包中拿到文件流
InputStream stream = resource.getInputStream();
StringBuilder buffer = new StringBuilder();
byte[] bytes = new byte[1024];
try {
for (int n; (n = stream.read(bytes)) != -1; ) {
buffer.append(new String(bytes, 0, n));
}
} catch (IOException e) {
e.printStackTrace();
}
txt = buffer.toString();
到此問題已經解決,想知道根本原因的繼續往下看下面鏈接的內容。
https://www.renfei.net/posts/1003293
因爲resourceUrl.getProtocol()不是file,而是 jar,這樣就拋出了一個FileNotFoundException異常。
ResouceUtils.getFile()是專門用來加載非壓縮和Jar包文件類型的資源,所以它根本不會去嘗試加載Jar中的文件,要想加載Jar中的文件,只要用可以讀取jar中文件的方式加載即可,比如 xx.class.getClassLoader().getResouceAsStream()這種以流的形式讀取文件的方式,所以使用讀取文件流就可以拿到了。