在 Java 專案中,正確獲取資源檔案的絕對路徑是常見需求。本文整理三種透過 Class.getResource() 取得路徑的方法,適用於不同場景。
this.getClass().getResource("/").getPath().substring(1)
// 結果範例:E:/myeclipse/test/WebRoot/WEB-INF/classes/
適用於讀取專案根目錄下的配置檔(如 application.properties)。
this.getClass().getResource("").getPath().substring(1)
// 結果範例:E:/myeclipse/test/WebRoot/WEB-INF/classes/net/hncu/db/
適用於讀取與當前類同目錄下的資源檔。
this.getClass().getResource(".").getPath().substring(1)
// 結果與方法二相同
getPath() 回傳的路徑前綴帶有 /,需用 substring(1) 移除(Windows 環境)\,Linux/Mac 為 /,建議使用 File.separator 處理跨平台相容getResource() 回傳 jar:file:... 格式,需改用 getResourceAsStream() 讀取流ServletContext.getRealPath() 獲取實體路徑// 跨平台、支援 JAR 打包的通用寫法
InputStream is = this.getClass().getResourceAsStream("/config.properties");
Properties props = new Properties();
props.load(is);