如何獲取springboot打成jar后的classpath
獲取springboot打成jar后的classpath
項目需要另一個子項目Utils的一個util工具類,在A項目的maven中加入了該子項目
<dependency> ?? ??? ??? ?<groupId>com.supconit.data.algorithm.platform</groupId> ?? ??? ??? ?<artifactId>data_algorithm_util</artifactId> ?? ??? ??? ?<version>1.1.00.190408-SNAPSHOT</version> </dependency>
但是該工具類的執(zhí)行依賴一個conf文件,把子項目Utils打成jar包后,發(fā)布到linux平臺上,發(fā)現(xiàn)無法讀取該配置文件
報錯如下:
java.io.FileNotFoundException: class path resource [fdfs_client.conf] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/data_algorithm/data_algorithm_executor-1.1.00.190408-SNAPSHOT.jar!/BOOT-INF/lib/data_algorithm_util-1.1.00.190408-SNAPSHOT.jar!/fdfs_client.conf
修改之前的代碼
?String path ?= new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath(); ?ClientGlobal.init(path);
修改之后的代碼
?ClassPathResource classPathResource = new ClassPathResource("fdfs_client.conf"); ? ? ? ? ? ? //創(chuàng)建臨時文件,將fdfs_client.conf的值賦值到臨時文件中,創(chuàng)建這個臨時文件的原因是springboot打成jar后無法獲取classpath下文件 ? ? ? ? ? ? String tempPath =System.getProperty("java.io.tmpdir") + System.currentTimeMillis()+".conf"; ? ? ? ? ? ? File f = new File(tempPath); ? ? ? ? ? ? IOUtils.copy(classPathResource.getInputStream(),new FileOutputStream(f)); ? ? ? ? ? ? ClientGlobal.init(f.getAbsolutePath());
發(fā)布之后,問題解決,原因是因為打包后Spring試圖訪問文件系統(tǒng)路徑,但無法訪問JAR中的路徑,因此必須使用resource.getInputStream()。
springboot打成jar后獲取classpath下文件異常解決
寫了一個工具類,要讀取classpath下的文件,使用
Resource resource = new ClassPathResource(filePath); File file = resource.getFile();
在本地測試,沒發(fā)現(xiàn)問題,但是將項目打包成jar包后運行,發(fā)現(xiàn)報錯
Caused by: java.io.FileNotFoundException: class path resource [test.txt] cannot be resolved to absolute file path because it does not reside in the file system: j
原因
打包后Spring試圖訪問文件系統(tǒng)路徑,但無法訪問JAR中的路徑。
解決
Resource resource = new ClassPathResource(filePath); InputStream inputStream = resource.getInputStream();
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Kotlin:forEach也能break和continue
這篇文章主要介紹了詳解Kotlin:forEach也能break和continue的相關(guān)資料,需要的朋友可以參考下2017-06-06springboot基于Mybatis mysql實現(xiàn)讀寫分離
這篇文章主要介紹了springboot基于Mybatis mysql實現(xiàn)讀寫分離,需要的朋友可以參考下2019-06-06Spring Cloud zuul自定義統(tǒng)一異常處理實現(xiàn)方法
這篇文章主要介紹了Spring Cloud zuul自定義統(tǒng)一異常處理實現(xiàn),需要的朋友可以參考下2018-02-02基于mybatis-plus timestamp返回為null問題的排除
這篇文章主要介紹了mybatis-plus timestamp返回為null問題的排除,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08