在我們編寫Java的應用程式時,可能會用到一些配置檔案,如config.properties,我們可以在配置檔案中存儲一些重要資訊,例如伺服器的IP位址,使用者名和密碼等資訊。
在本篇文章當中,隻是讨論如何擷取到資源檔案的路徑,并不會對資源檔案的内容進行讀取。
1、資源目錄:src目錄和bin目錄
在我們編寫Java代碼的過程當中,我們會把有關的資源檔案(例如config.properties)放到src目錄和src目錄下的某個package中。
但有一點值得注意的是,雖然我們在放置資源檔案的時候是在src目錄下,但是當我們對資源檔案進行讀取的時候,卻是在(與src同級的)bin目錄下。
換句話說,當我們添加資源檔案的時候,是在src目錄下,但是當程式運作的時候,會将src目錄下的資源複制到bin目錄下,是以程式通路的資源檔案是位于bin目錄下的。
在進行代碼通路之前,讓我來做一些準備,準備三個檔案。
第一個檔案位于com.rk.io下的config.properties檔案,其内容如下:
第二個檔案位于com.rk.io.property下的config.properties檔案,其内容如下:
第三個檔案位于com.rk.io.property.subdirectory下的config.properties檔案,其内容如下:
2、通過java.lang.Class類的getResource方法通路資源
代碼如下:
輸出結果:
3、通過java.lang.ClassLoader的getResource方法通路資源
4、對比java.lang.Class和java.lang.ClassLoader的getResource方法
對于java.lang.Class類的getResource方法,在傳入的參數中:
如果隻有一個"/config.properties",則表示bin目錄下的config.properties檔案;
如果輸入"/com/rk/io/config.properties",則表示在bin目錄下的com/rk/io内的config.propertiesy檔案。
如果輸入"config.properties",則表示與目前類的.class檔案在同一目錄當中的config.properties;
如果輸入"../config.properties",則表示目前類的.class的父目錄中的config.properties檔案。
對于java.lang.ClassLoader的getResource方法,其有一段英文描述如下:
Finds the resource with the given name. A resource is some data (p_w_picpaths, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.
用這個方法,資源檔案的位置和class code之間是彼此獨立的(a resource is some data that can be accessed by class code in a way that is independent of the location of the code)