共計 649 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用以下方法來獲取項目路徑:
- 使用 System.getProperty(“user.dir”) 方法來獲取當前工作目錄的路徑,即項目的根目錄路徑。
String projectPath = System.getProperty("user.dir");
System.out.println(" 項目路徑:" + projectPath);
- 使用 ClassLoader 類的 getResource() 方法來獲取項目中的資源文件路徑。
ClassLoader classLoader = getClass().getClassLoader();
String resourcePath = classLoader.getResource("").getPath();
System.out.println(" 項目資源文件路徑:" + resourcePath);
- 使用 File 類的 getAbsolutePath() 方法獲取指定文件的絕對路徑,從而間接獲取項目路徑。
String filePath = "src/main/java/com/example/Main.java";
File file = new File(filePath);
String projectPath = file.getAbsolutePath().replace(filePath, "");
System.out.println(" 項目路徑:" + projectPath);
這些方法可以幫助你獲取項目的路徑,從而方便地操作項目中的文件和資源。
丸趣 TV 網 – 提供最優質的資源集合!
正文完