引言
在web項目開發過程中,可能會經常遇到要獲取項目根路徑的情況,那接下來我就總結一下,java中獲取項目根路徑的7種方法,主要是通過thisClass和System,線程和request等方法。
(1):this.getClass().getResource("/");
(2):file.getCanonicalPath();
(3):this.getClass().getClassLoader();
(4):System.getProperty("user.dir");
(5):System.getProperty("java.class.path");
(6):Thread.currentThread().getContentClassLoader();
(7):request.getSession().getServletContext();
代碼如下:
import java.io.File; import java.io.IOException; import java.net.URL; /*
*獲取項目根路徑的方法
*/ public class MyUrlDemo { public static void main(String[] args) { MyUrlDemo muDemo = new MyUrlDemo(); try { muDemo.showURL(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void showURL() throws IOException { // 第一種:獲取類加載的根路徑 D:\git\daotie\daotie\target\classes File f = new File(this.getClass().getResource("/").getPath()); System.out.println("path1: "+f); // 獲取當前類的所在工程路徑; 如果不加“/” 獲取當前類的加載目錄 D:\git\daotie\daotie\target\classes\my File f2 = new File(this.getClass().getResource("").getPath()); System.out.println("path1: "+f2); // 第二種:獲取項目路徑 D:\git\daotie\daotie File directory = new File("");// 參數為空 String courseFile = directory.getCanonicalPath(); System.out.println("path2: "+courseFile); // 第三種: file:/D:/git/daotie/daotie/target/classes/ URL xmlpath = this.getClass().getClassLoader().getResource(""); System.out.println("path3: "+xmlpath); // 第四種: D:\git\daotie\daotie System.out.println("path4:" +System.getProperty("user.dir")); /* * 結果: C:\Documents and Settings\Administrator\workspace\projectName * 獲取當前工程路徑 */ // 第五種: 獲取所有的類路徑 包括jar包的路徑 System.out.println("path5: "+System.getProperty("java.class.path").split(";")[0]);
// 第六種: 獲取項目路徑 D:/git/daotie/daotie.target/classes/
System.out.println("path6: "+Thread.currentThread().getContentClassLoader().getResource("").getPath());
//第七種 表示到項目的根目錄下, 要是想到目錄下的子文件夾,修改"/"即可
String path7 = request.getSession().getServletContext().getRealPath("/"));
System.out.pringln("path7: "+path7);
} }
結果: