springboot項目打成jar包後 沒法獲取static下的靜態資源文件

springboot 後端項目 作某個功能時 須要讀取根目錄下的.doc文件,具體項目中路徑以下:java

開始是經過絕對路徑讀取文檔,在開發環境沒有任何問題。spring

可是 將項目打成jar包 部署到測試環境發現不管怎樣都讀取不到,而後在本地運行jar包出現一樣的狀況。apache

捕獲到的異常:後端

[org.apache.ibatis.session.defaults.DefaultSqlSession@55b40849]
java.io.FileNotFoundException: class path resource [static/****.doc] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/**/***/target/****-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static/****.doc

緣由:
此時運行中的Java程序實際上是在讀取jar包中的文件,直接使用下面的方式是不行的:springboot

常見的獲取路徑寫法:session

好比文件路徑 src\main\resources\static\***.doc
String path = this.getClass().getClassLoader().getResource("").getPath()+"/static/***.doc";
File file = new File(path);

在java中,若是應用打成jar包後,應用運行後須要讀取本jar包以內的文件,更換寫法:ide

經過類加載器的getResourceAsStream方法,讓jar讀取到本身的資源文件
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/***.doc");

便可。測試

相關文章
相關標籤/搜索