java代碼中擷取classpath路徑

來源:互聯網
上載者:User

標籤:cat   知識   getpath   tail   system   classes   sdn   domain   java   

Java web工程中,有時候需要自己手動的去讀取classpath下面的設定檔,這裡總結一點讀取classpath路徑的方法,分享一下。


方法一:

[html] view plain copy
  1. String path = Test.class.getResource("/").toString();   
  2. System.out.println("path = " + path);  

此方法在tomcat下面沒有問題,可以取到WEB-INF/classes

path = file:/home/ngidm_db2/AS_Tomcat7_0_29/webapps/NGIDM/WEB-INF/classes/

但換weblogic之後,取到的為

path = file:/Oracle/weblogic/Oracle/Middleware/Oracle_Home/user_projects/domains/base_domain/

在weblogic下面,沒能拿到classes路徑。


方法二:

[html] view plain copy
  1. String path2 = Thread.currentThread().getContextClassLoader().getResource("/").getPath();  
  2. System.out.println("path2 = " + path2);  


在tomcat和weblogic下面均可取到classes路徑

path2 = /oracle/weblogic/Oracle/Middleware/user_apps/NGIDM/WEB-INF/classes/

path2 = /home/ngidm_db2/AS_Tomcat7_0_29/webapps/NGIDM/WEB-INF/classes/

故建議大家多使用

Thread.currentThread().getContextClassLoader().getResource("/").getPath();

擷取classpath路徑,且方法2 取到的classpath不含file:首碼,可以直接使用。    

java代碼中擷取classpath路徑

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.