Java擷取工程目錄

來源:互聯網
上載者:User

標籤:tab   this   tom   contex   get   loader   getpath   方法   配置   

背景:程式執行時,會涉及到去讀取設定檔等操作,那就需要瞭解怎麼獲得檔案路徑 Java目錄映射關係說明一點:在Java代碼執行時,會將編譯產生的classes檔案,以及設定檔等資訊產生到target目錄下。最終執行的檔案實際是target下的class檔案以的例子為例:工程名:zzappqa工程所在目錄:/opt/script/zzappqa產生的target目錄:target 下面是一個工程檔案到產生的target目錄的一個映射關係zzappqa工程下的檔案target下的檔案源碼java檔案classes下的class檔案資源檔resourcesclasses下web網站的資源檔webappzzappqa(工程名)

 

zzappqa工程下的檔案 target下的檔案
源碼java檔案 classes下的class檔案
資源檔resources classes下
web網站的資源檔webapp zzappqa(工程名)

一般設定檔都是放在資源檔resources下的,綜上關係,如果想獲得設定檔。只要找到target下的classes目錄即可。 擷取classes目錄位址的方法:this.getClass().getResource("/").getPath()  擷取工程目錄的方法說明:web網站,在本地和在tomcat啟動時,System.getProperty("user.dir")是不一致的 
方法 說明
System.getProperty("user.dir") 1、如果是本地執行的,擷取的是工程根目錄2、如果是在tomcat中啟動的,獲得的是tomcat的bin目錄
Thread.currentThread().getContextClassLoader().getResource("").toString()) 獲得java編譯檔案存放的classes根目錄資源檔resources也在該目錄下
this.class.getClassLoader().getResource("").getPath() 同上獲得java編譯檔案存放的classes根目錄資源檔resources也在該目錄下
this.class.getClass().getResource("/").getPath() 同上獲得java編譯檔案存放的classes根目錄資源檔resources也在該目錄下
this.class..getClass().getClassLoader().getResource(".").getPath() 同上獲得java編譯檔案存放的classes根目錄資源檔resources也在該目錄下
this.class.getClass().getResource("/comm").getPath() 獲得classes目錄下的comm路徑註:如果該路徑不存在會拋null 指標異常
System.getProperty("java.class.path") 獲得java所有類載入路徑

 

Java擷取工程目錄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.