java代码中获取classpath路径

参考:http://blog.csdn.net/magi1201/article/details/18731581

方法一:

 

[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:前缀,可以直接使用。

posted on 2017-01-03 15:20  struggle_beiJing  阅读(3483)  评论(1编辑  收藏  举报

导航