共計(jì) 628 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
在 Java 中,可以使用以下方法來(lái)獲取項(xiàng)目路徑:
- 使用
System.getProperty("user.dir")
方法來(lái)獲取當(dāng)前工作目錄的路徑,即項(xiàng)目的根目錄。
String projectPath = System.getProperty("user.dir");
System.out.println(" 項(xiàng)目路徑:" + projectPath);
- 使用
Class.getResource()
方法來(lái)獲取指定資源的 URL,然后通過(guò)該 URL 獲取其所在的目錄路徑。
URL resourceUrl = MyClass.class.getResource("/");
String projectPath = resourceUrl.getPath();
System.out.println(" 項(xiàng)目路徑:" + projectPath);
請(qǐng)注意,上述代碼中的 MyClass
應(yīng)替換為你自己的類名。
- 使用
ClassLoader.getSystemResource()
方法來(lái)獲取指定資源的 URL,然后通過(guò)該 URL 獲取其所在的目錄路徑。
URL resourceUrl = ClassLoader.getSystemResource("");
String projectPath = resourceUrl.getPath();
System.out.println(" 項(xiàng)目路徑:" + projectPath);
以上方法可以根據(jù)不同的需求選擇使用,根據(jù)你的具體情況選擇最適合的方法獲取項(xiàng)目路徑。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完