1. 程式人生 > 其它 >springboot讀取resource目錄下檔案

springboot讀取resource目錄下檔案

FileNotFoundException: class path resource [static/download/template.xlsx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/.jar!/BOOT-INF/classes!/static/download/template.xlsx

報錯的程式碼

File file = ResourceUtils.getFile("classpath:static/download/template.xlsx"
);

ResourceUtils.getFile原始碼如下:
在這裡插入圖片描述
在這裡插入圖片描述
而resourceUrl.getProtocol() = “jar” 所以報錯
這是因為springboot打成jar包執行,Resource下的檔案是存在於jar這個檔案裡面,在磁碟上是沒有真實路徑存在的,它其實是位於jar內部的一個路徑。所以通過ResourceUtils.getFile或者this.getClass().getResource("")方法無法正確獲取檔案。
解決辦法:以檔案流的方式讀取jar中檔案

將文件放在專案外,應用可以讀取到的一個固定目錄。按正常的方式讀取即可,但可維護性比較差,很容易被誤操作丟失。

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource resource = resolver.getResource("static/download/template.xlsx");
InputStream inputStream = resource.getInputStream();
ClassPathResource classPathResource = new ClassPathResource("static/download/template.xlsx"
); InputStream inputStream1 = classPathResource.getInputStream();