Java中獲取項目根路徑和類加載路徑的7種方法


引言

    在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);
} }

 結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM