SpringBoot打成jar包后無法讀取resources資源文件里文件路徑的問題 cannot be resolved to absolute file path because it does


SpringBoot打成jar包后無法讀取resources資源文件

在項目中做了一個支付功能, 需要引入第三方渠道的配置文件config.xml用來初始化文件證書, 將配置文件 config.xml 放到 resources 資源目錄下。

本地開發環境下能正常讀取該文件, 但是在 Linux 環境下將項目打包成jar后運行會出現如下異常:

java.io.FileNotFoundException: class path resource [static/config.xml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/ROOT/xxx.jar!/BOOT-INF/lib/xxx-2.1.jar!/static/config.xml 
    at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:217) 
    at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:154) 
   ...

因為在本地開發環境下, config.xml是真實存在於磁盤上的某個目錄, 此時通過  new File(文件路徑)  是可以正常讀取的。

但是在Linux下打包成jar后, 實際上config.xml是存在於jar里面的資源文件, 在磁盤上是沒有真實路徑存在的, 所以通過文件讀取文件讀取方式會報  java.io.FileNotFoundException 

對此, Java API提供了一些方法, 可以通過I/O流的方式先獲取這個文件流, 再將這個文件流寫入到一個真實存在的指定磁盤路徑, 這樣我們就可以通過  new File() 讀取文件的方式訪問了.

復制代碼

    ApplicationHome applicationHome = new ApplicationHome(CcbImpl.class);
    //項目打包成jar包所在的根路徑
    String rootPath = applicationHome.getSource().getParentFile().toString();
    String configFilePath = rootPath + "/xxx/xxx/config.xml";
    File configFile = new File(configFilePath);
    if (!configFile.exists()) {
        try {
         //獲取類路徑下的指定文件流
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("static/config.xml");
            FileUtils.copyInputStreamToFile(Objects.requireNonNull(in, "config.xml文件找不到"), configFile);
        } catch (IOException e) {
            throw new IllegalArgumentException("保存文件證書失敗->" + ExceptionUtils.getStackTraceAsString(e));
        }
    }

復制代碼


免責聲明!

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



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