共計 751 個字符,預計需要花費 2 分鐘才能閱讀完成。
Java 中可以使用以下方法來獲取當前程序的路徑:
1. 使用 System.getProperty("user.dir")
方法,它會返回當前程序的工作目錄路徑。
2. 使用 File
類的 getAbsolutePath()
方法,可以通過創建一個 File
對象來獲取當前程序的絕對路徑。
3. 使用 ClassLoader
類的 getResource()
方法,可以獲取當前程序所在的類路徑(classpath)的 URL,進而通過 URL
對象的 getPath()
方法獲取路徑字符串。
下面是示例代碼:java
// 方法 1
String currentDir = System.getProperty("user.dir");
System.out.println(" 當前程序路徑:" + currentDir);
// 方法 2
File currentFile = new File("");
String currentPath = currentFile.getAbsolutePath();
System.out.println(" 當前程序路徑:" + currentPath);
// 方法 3
ClassLoader classLoader = MyClass.class.getClassLoader(); // 這里的 MyClass 替換為當前類的名稱
URL url = classLoader.getResource("");
String currentPath = url.getPath();
System.out.println(" 當前程序路徑:" + currentPath);
請注意,以上代碼中的路徑是當前程序的路徑,而不是某個特定類的路徑。如果需要獲取某個類的路徑,可以使用 MyClass.class.getResource("")
來替換方法 3 中的代碼。
丸趣 TV 網 – 提供最優質的資源集合!