亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

如何獲取springboot打成jar后的classpath

 更新時(shí)間:2023年07月21日 15:16:30   作者:琴瑟裹腹  
這篇文章主要介紹了如何獲取springboot打成jar后的classpath問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

獲取springboot打成jar后的classpath

項(xiàng)目需要另一個(gè)子項(xiàng)目Utils的一個(gè)util工具類(lèi),在A項(xiàng)目的maven中加入了該子項(xiàng)目

<dependency>
?? ??? ??? ?<groupId>com.supconit.data.algorithm.platform</groupId>
?? ??? ??? ?<artifactId>data_algorithm_util</artifactId>
?? ??? ??? ?<version>1.1.00.190408-SNAPSHOT</version>
</dependency>

但是該工具類(lèi)的執(zhí)行依賴(lài)一個(gè)conf文件,把子項(xiàng)目Utils打成jar包后,發(fā)布到linux平臺(tái)上,發(fā)現(xiàn)無(wú)法讀取該配置文件

報(bào)錯(cuò)如下:

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)建臨時(shí)文件,將fdfs_client.conf的值賦值到臨時(shí)文件中,創(chuàng)建這個(gè)臨時(shí)文件的原因是springboot打成jar后無(wú)法獲取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ā)布之后,問(wèn)題解決,原因是因?yàn)榇虬骃pring試圖訪(fǎng)問(wèn)文件系統(tǒng)路徑,但無(wú)法訪(fǎng)問(wèn)JAR中的路徑,因此必須使用resource.getInputStream()。

springboot打成jar后獲取classpath下文件異常解決

寫(xiě)了一個(gè)工具類(lèi),要讀取classpath下的文件,使用

Resource resource = new ClassPathResource(filePath);
File file = resource.getFile();

在本地測(cè)試,沒(méi)發(fā)現(xiàn)問(wèn)題,但是將項(xiàng)目打包成jar包后運(yùn)行,發(fā)現(xiàn)報(bào)錯(cuò)

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試圖訪(fǎng)問(wèn)文件系統(tǒng)路徑,但無(wú)法訪(fǎng)問(wèn)JAR中的路徑。

解決

Resource resource = new ClassPathResource(filePath);
InputStream inputStream = resource.getInputStream();

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論