Spring boot 打包jar后無法讀取resource下的配置文件


在開發的spring boot項目中,需要讀取一個*.conf文件。

在idea中運行項目不報任何錯誤,打包jar后報找不到文件的異常。

原因:jar是一個壓縮包,jar包中的文件在磁盤中是沒有真實路徑的,因此找不到代碼中的路徑文件。

解決思路:通過文件流的讀取方式,代碼中將*.conf文件拷貝至jar外的臨時文件夾下,然后再讀取臨時文件夾下的*.conf文件。

核心代碼:

 1 public TrackerClient getTrackerClient(){
 2         InputStream in=null;
 3         OutputStream os=null;
 4         try{
 5             //將文件轉化為輸入流的形式
 6             ClassPathResource classPathResource = new ClassPathResource("fastdfs/fdfs_client.conf");
 7             in=classPathResource.getInputStream();
 8             //項目打包成jar包所在的根路徑
 9             String rootPath = System.getProperty("user.dir");
10             String tempPath=rootPath+ File.separator +"fdfs_client.conf";
11             log.info("fdfs_client.conf*****************"+tempPath+"******************");
12             //將文件復制到這個路徑
13             os=new FileOutputStream(tempPath);
14             byte[] flush = new byte[1024];
15             int len = -1;
16             // 邊讀邊寫
17             while ((len = in.read(flush)) != -1) {
18                 os.write(flush, 0, len);
19             }
20             ClientGlobal.init(tempPath);
21             // 創建一個TrackerClient對象。
22             TrackerClient trackerClient = new TrackerClient();
23             return  trackerClient;
24         }catch (Exception e){
25             log.info("###獲取TrackerClient異常!###",e);
26             return null;
27         }finally {
28             if(in!=null){
29                 try {
30                     in.close();
31                 } catch (IOException e) {
32                     log.error("###文件關閉失敗!###",e);
33                 }
34             }
35             if(os!=null){
36                 try {
37                     os.close();
38                 } catch (IOException e) {
39                     log.error("###文件關閉失敗!###",e);
40                 }
41             }
42         }
43     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM