Java 如何讀取resources

來源:互聯網
上載者:User

標籤:bootstra   工程   測試   resources   pac   分割   sam   system   存在   

Sample in Github

1.一般使用Maven建立Java工程,代碼檔案在src/main/java檔案夾中,資源檔在src/main/resources檔案夾中,Java代碼為什麼可以讀取到src/main/resources下的資源檔呢?

=> Maven會將Java工程編譯到target檔案夾下,/target/classes應該就是其根目錄。編譯後發現,.class檔案就在這個檔案夾下的對應子檔案夾中,而src/main/resources下的檔案被複製到了這個檔案夾下。

 

2. src/test/java目錄下的測試代碼,又是如何讀取resources的呢?

=> Maven會將src/test/java檔案夾下的代碼編譯到target/test-classes檔案夾下。同樣的,如果src/test/resources下有資源檔的話,就複製到target/test-classes檔案夾下。

測試代碼運行時,優先使用test-classes檔案夾下的資源檔,如果不存在,再使用classes檔案夾下的資源檔。

 

  public void loadProperties1() throws IOException {    InputStream input = null;    // read from the root folder    input = this.getClass().getResourceAsStream("/config.properties");        // InputStream java.lang.Class.getResourceAsStream(String name)    // 1.首先,根據資源名稱構造出一個絕對的資源路徑    //   如果資源名稱以‘/‘開頭,資源的絕對名稱就是‘/‘之後的名稱部分    //   否則,就是modified_package_name/name    //   modified_package_name就是這個類的包名,其中的‘.‘換為‘/‘    // 2.然後,尋找資源的規則是由類的class loader實現的。    //   如果這個類是由bootstrap類載入器載入的話,就會用ClassLoader.getSystemResourceAsStream.    printProperties(input);  }    public void loadProperties2() throws IOException {    InputStream input = null;        input = this.getClass().getClassLoader().getResourceAsStream("config2.properties");    // URL java.lang.ClassLoader.getResource(String name)    // 資源名就是由‘/‘分割的資源的路徑名    // 首先尋找父類載入器    // 如果父是null,就尋找內建到VM中的該類載入器的路徑    // 失敗的話,調用 findResource(String)        printProperties(input);  }

  

Java 如何讀取resources

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.