java代码中获取classpath路径


下载ava web工程中,有时候需要自己手动的去读取classpath下面的配置文件,这里总结一点读取classpath路径的方法,分享一下
方法一: 

Java代码 下载
  1. String path = Test.class.getResource("/").toString();     
  2. System.out.println("path = " + path);    
String path = Test.class.getResource("/").toString();   
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路径。
方法二: 

  1. String path2 = Thread.currentThread().getContextClassLoader().getResource("/").getPath();    
  2. System.out.println("path2 = " + path2);    
String path2 = Thread.currentThread().getContextClassLoader().getResource("/").getPath();  
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/ 故建议大家多使用

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

获取classpath路径,且方法2 取到的classpath不含file:前缀,可以直接使用。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM