一、背景
最近有個(gè)需求,就是需要從resource目錄下讀取文件返回給用戶。在idea中運(yùn)行時(shí),有些resource下文件讀取工具類能夠正常獲取讀取到文件。但是通過java –jar的方式去運(yùn)行jar包,此時(shí)resource下文件讀取工具類讀取文件就失效了。通過查詢搜索,了解到了是讀取的方式導(dǎo)致文件讀取失敗。
二、具體代碼實(shí)現(xiàn)
1、錯(cuò)誤的resource下文件讀取寫法
這部分代碼展示的是通過運(yùn)行jar包,ClassPathResource工具無法正常讀取到文件
// 讀取resource目下腳本模板文件
String templatePath = "/script/test.py";
ClassPathResource resource = new ClassPathResource(templatePath);
File file;
try {
file = resource.getFile();
} catch (IOException e) {
e.printStackTrace();
}
此處的主要做法是:通過ClassPathResource定位到resource目錄下的文件,再通過他去拿到File類型的文件,通過實(shí)踐證明,拿到的File是空的,說明這種方式獲取文件存在問題。
2、正確的resource下文件讀取寫法
// 讀取resource目下腳本模板文件
String templatePath = "/script/test.py";
ClassPathResource resource = new ClassPathResource(templatePath);
BufferedInputStream bis = new BufferedInputStream(resource.getInputStream());
以上的主要做法是:通過ClassPathResource定位到resource目錄下的文件,我們只需要從ClassPathResouce對(duì)象中拿到輸入流即可,通過實(shí)踐證明,通過這種方式能夠正常拿到文件輸入流。
三、問題分析
為什么在打成jar包之后,不支持文件通過File定位,只能通過流或在其他方式,抱著疑惑的態(tài)度,我進(jìn)入ClassPathResource類查看是否有什么提示,結(jié)果還真找到了,看如下:
**
* {@link Resource} implementation for class path resources. Uses either a
* given {@link ClassLoader} or a given {@link Class} for loading resources.
*
* <p>Supports resolution as {@code java.io.File} if the class path
* resource resides in the file system, but not for resources in a JAR.
* Always supports resolution as URL.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 28.12.2003
* @see ClassLoader#getResourceAsStream(String)
* @see Class#getResourceAsStream(String)
*/
public class ClassPathResource extends AbstractFileResolvingResource {
定位這一句話:
* <p>Supports resolution as {@code java.io.File} if the class path
* resource resides in the file system, but not for resources in a JAR.
* Always supports resolution as URL.
百度大致翻譯如下:
如果類路徑資源駐留在文件系統(tǒng)中,則支持解析為java.io.File,但不支持JAR中的資源。始終支持URL解析)。
所以大致可以理解為,我們通過java –jar運(yùn)行的方式,是無法將resource下的文件解析為java.io.File的。所以當(dāng)我們使用ClassPathResouce時(shí),就可以從中讀取到文件流,或者轉(zhuǎn)化為URL方式進(jìn)行讀取。
至于為什么不能解析為java.io.File,這個(gè)感興趣的小伙伴可以去探索一下(我大概猜測(cè)一下:jar包就是一個(gè)壓縮包,在壓縮的情況下無法解析到文件路徑,而且也無法通過File去定位到j(luò)ar包中的文件)。
四、其他方式讀取resource目錄下文件
InputStream inputStream = this.getClass().getClassLoader().getResource("/script/test.py"
).openStream();
InputStream inputStream = this.getClass().getResourceAsStream("/script/test.py");
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/script/test.py");
InputStream?inputStream = ResourceUtils.getURL("classpath:script/test.py").openStream();
總結(jié):可以看出,以上最終都是通過resource相關(guān)工具定位到文件后,從中拿到輸入流進(jìn)行讀取的。文章來源:http://www.zghlxwxcb.cn/news/detail-450631.html
好了,以上就是讀取jar包中resouce目錄下文件的解決方式了,還有更多其他的讀取方式,歡迎小伙伴們?cè)u(píng)論區(qū)留言討論。文章來源地址http://www.zghlxwxcb.cn/news/detail-450631.html
到了這里,關(guān)于Spring?Boot讀取resource目錄下文件失敗解決方案及分析的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!