gqinvs 发表于 2017-2-18 11:51:13

java代码中获取classpath路径

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


[*]String path = Test.class.getResource("/").toString();   
[*]System.out.println("path = " + path);   

String path = Test.class.getResource("/").toString();   
System.out.println("path = " + path);
  此方法在tomcat下面没有问题,可以取到WEB-INF/classespath = 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路径。
方法二:


[*]String path2 = Thread.currentThread().getContextClassLoader().getResource("/").getPath();   
[*]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/ 故建议大家多使用


[*]Thread.currentThread().getContextClassLoader().getResource("/").getPath();

Thread.currentThread().getContextClassLoader().getResource("/").getPath();
  获取classpath路径,且方法2 取到的classpath不含file:前缀,可以直接使用。
页: [1]
查看完整版本: java代码中获取classpath路径