共計 757 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以通過多種方式獲取項目路徑:
- 使用
System.getProperty("user.dir")
方法獲取當前工作目錄的絕對路徑。這個路徑通常是運行 Java 程序時所在的目錄。
String projectPath = System.getProperty("user.dir");
System.out.println(projectPath);
- 使用
Class.getResource()
方法獲取類所在的路徑。這個路徑是相對于類所在的包的路徑。
String projectPath = MyClass.class.getResource("").getPath();
System.out.println(projectPath);
- 使用
ClassLoader.getResource()
方法獲取類加載器所在的路徑。這個路徑是相對于類加載器的根路徑。
ClassLoader classLoader = MyClass.class.getClassLoader();
String projectPath = classLoader.getResource("").getPath();
System.out.println(projectPath);
- 使用
ServletContext.getRealPath()
方法獲取 Web 應用的根路徑。這個路徑是 Web 容器運行時動態計算的。
ServletContext servletContext = getServletContext();
String projectPath = servletContext.getRealPath("/");
System.out.println(projectPath);
注意:以上方法中獲取的路徑都是字符串,可以根據需要進行進一步的處理。
丸趣 TV 網 – 提供最優質的資源集合!
正文完