在 Java 開發中,正確獲取類路徑對於資源載入、配置文件讀取至關重要。本文整理 4 種常見方法,並說明其適用場景與差異。
String path = System.getProperty("java.class.path");
特點:返回 JVM 啟動時的完整 classpath 字串,包含所有依賴 JAR 路徑,以系統分隔符分隔。
適用:診斷環境配置、啟動腳本驗證。
String path = MyClass.class.getProtectionDomain()
.getCodeSource().getLocation().getPath();
特點:返回該類文件實際物理位置(JAR 檔或目錄)。
注意:getPath() 返回 URL 路徑,getFile() 返回文件路徑,兩者在特殊字符編碼上有差異。
String path = Thread.currentThread().getContextClassLoader()
.getResource("").getPath();
特點:返回當前線程上下文類加載器的根資源路徑,通常指向 classes 目錄或 JAR 根目錄。
適用:Web 容器、模塊化應用中獲取當前模塊資源路徑。
public class ClasspathDemo {
public static void main(String[] args) {
System.out.println("===== Classpath 測試 =====");
System.out.println("1. System Property: " + System.getProperty("java.class.path"));
System.out.println("2. CodeSource Path: " + ClasspathDemo.class.getProtectionDomain().getCodeSource().getLocation().getPath());
System.out.println("3. CodeSource File: " + ClasspathDemo.class.getProtectionDomain().getCodeSource().getLocation().getFile());
System.out.println("4. ContextClassLoader: " + Thread.currentThread().getContextClassLoader().getResource("").getPath());
System.out.println("==========================");
}
}
| 場景 | 推薦方法 |
|---|---|
| 獲取完整啟動路徑 | 方法 1 |
| 定位特定類/資源物理位置 | 方法 2 |
| Web/企業級應用資源載入 | 方法 3 |
| 跨平台路徑處理 | 搭配 URLDecoder.decode(path, "UTF-8") 解碼 |
/(如 /C:/path),需手動裁剪file:/path/to.jar!/ 格式掌握這些方法差異,能讓資源定位更精準、部署遷移更順利。