1. 程式人生 > >java獲取程式根目錄 WEB-INFO目錄 CLASSES資料夾路徑

java獲取程式根目錄 WEB-INFO目錄 CLASSES資料夾路徑

嘗試用DOM4j解析spring配置檔案時,第一步讀取檔案時,獲取路徑就遇到了問題,。。。經過google了n+log n 次個頁面,才算有了個粗淺的認識,下面就讓我用簡短的話語來總結一下(好像這段就全是廢話。。。)。。。

1、spring的配置檔案存放位置由web.xml裡的contextConfigLocation來確定,一般是放在web-inf或者是src根目錄下

2、關於src資料夾裡的檔案的釋出:source folder下的.java檔案,生成的.class檔案放在output folder中。而將source folder中的非.java檔案直接拷貝到output folder(eclipse會直接拷貝全部的非.java檔案,intellij IDEA可以配置拷貝哪些副檔名的檔案)。 output資料夾一般指的是c/s的bin和b/s的classes。

3、用SAXReader.reader讀取時需要知道檔案的路徑 。

我列出一段程式碼,大家感受一下吧

01.System.out.println(this.getClass().getClassLoader().getResource("com/lavasoft/res/a.txt"));  
02.    System.out.println(this.getClass().getResource("/com/lavasoft/res/a.txt"));  
03.    System.out.println(this.getClass().getResource("").getPath());   
04.    System.out.println(this.getClass().getResource("/").getPath());   
05.    System.out.println(this.getClass().getClassLoader().getResource("").getPath());  
06.   System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath());  
07.    System.out.println(System.getProperty("user.dir")); 
System.out.println(this.getClass().getClassLoader().getResource("com/lavasoft/res/a.txt"));
 System.out.println(this.getClass().getResource("/com/lavasoft/res/a.txt"));
 System.out.println(this.getClass().getResource("").getPath());
 System.out.println(this.getClass().getResource("/").getPath());
 System.out.println(this.getClass().getClassLoader().getResource("").getPath());
 System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath());
 System.out.println(System.getProperty("user.dir"));

getclass()是當前的類例項,得到的是src下當前類的目錄;getclassloader()是類的裝載器,得到的是src根目錄。"/"表示的是根目錄。

web-inf目錄如何取得還在摸索中,各位有知道的,請不吝賜教。

最後貼一篇我感覺總結得很好的文章:

再來一篇 類載入路徑 原理的文章 jwitch:

還有這篇也需要研究一下: