1. 程式人生 > 程式設計 >解決SpringBoot打成jar執行後無法讀取resources裡的檔案問題

解決SpringBoot打成jar執行後無法讀取resources裡的檔案問題

開發一個word替換功能時,因替換其中的內容功能需要 word 模版,就把 word_replace_tpl.docx 模版檔案放到 resources 下

解決SpringBoot打成jar執行後無法讀取resources裡的檔案問題

在開發環境中通過下面方法能讀取word_replace_tpl.docx檔案,但是打成jar包在 linux下執行後無法找到檔案了

File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/office_template/xxx.docx");

在開發環境執行時,會把資原始檔編譯到 專案\target\classes\static\office_template\xxx.docx 目錄下,但是打包成jar後,

Resource下的檔案是存在於jar這個檔案裡面,在磁碟上是沒有真實路徑存在的,它是位於jar內部的一個路徑。所以通過ResourceUtils.getFile或者this.getClass().getResource("")方法無法正確獲取檔案。

我們用壓縮軟體開啟 jar 檔案,看看該word模版位於jar內部的路徑在這裡插入圖片描述

解決SpringBoot打成jar執行後無法讀取resources裡的檔案問題

怎麼解決

1.把該模版檔案放到jar專案外,在專案中配置該模版檔案的絕對路徑,不太推薦這種方式,可能會忘記配置模版

2.通過 ClassPathResource resource = new ClassPathResource(“static/office_template/word_replace_tpl.docx”);方式讀取

用第二種方式讀取jar中的檔案流

ClassPathResource resource = new ClassPathResource("static/office_template/word_replace_tpl.docx");
File sourceFile = resource.getFile();
InputStream fis = resource.getInputStream();

還要在專案pom.xml中配置resources情況

<build>
 <!-- 定義包含這些資原始檔,能在jar包中獲取這些檔案 -->
 <resources>
 <resource>
 <directory>src/main/java</directory>
 <includes>
 <include>**/*.properties</include>
 <include>**/*.xml</include>
 <include>**/*.yml</include>
 </includes>
 <!--是否替換資源中的屬性-->
 <filtering>false</filtering>
 </resource>
 <resource>
 <directory>src/main/resources</directory>
 <includes>
 <include>**/*.*</include>
 </includes>
 <!--是否替換資源中的屬性-->
 <filtering>false</filtering>
 </resource>
 </resources>
 </build>

再次釋出專案,訪問功能,測試後已經在伺服器上能讀取模版檔案並生成出新檔案了

補充知識:兩個list高效取出其中新增和相同的數

兩個list迴圈,儘量避免雙層迴圈以及contains的使用

public static void test(){
    List<Integer> oldList = new ArrayList<Integer>(){{add(1);add(2);add(4);add(5);}};
    List<Integer> newList = new ArrayList<Integer>(){{add(3);add(4);add(5);add(6);}};
    Map<Integer,Integer> map = new HashMap<>();

    for (Integer i: oldList ) {
      map.put(i,0);
    }
    System.out.print(map);

    for (Integer j: newList ) {

      //value為1 ,更新的資料
      if (map.containsKey(j)){
        map.put(j,1);
      }else {
        //value為2 ,新增的資料
        map.put(j,2);
      }
    }
    System.out.println(map);
    for (Map.Entry<Integer,Integer> entry: map.entrySet() ) {
      if(entry.getValue().equals(0)){
        System.out.println("舊的值:"+entry.getKey());
      }
      if(entry.getValue().equals(1)){
        System.out.println("更新的值:"+entry.getKey());
      }
      if(entry.getValue().equals(3)){
        System.out.println("新增的值:"+entry.getKey());
      }
    }

    System.out.println(map);
  }

  public static void main(String[] arg){
    test();
  }

以上這篇解決SpringBoot打成jar執行後無法讀取resources裡的檔案問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。