標籤: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