引言java
在web項目開發過程當中,可能會常常遇到要獲取項目根路徑的狀況,那接下來我就總結一下,java中獲取項目根路徑的7種方法,主要是經過thisClass和System,線程和request等方法。git
(1):this.getClass().getResource("/");web
(2):file.getCanonicalPath();this
(3):this.getClass().getClassLoader();spa
(4):System.getProperty("user.dir");.net
(5):System.getProperty("java.class.path");線程
(6):Thread.currentThread().getContentClassLoader();code
(7):request.getSession().getServletContext();xml
代碼以下:blog
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);
} }
結果: