Obtain the classpath path in java code, javaclasspath
In the download of the ava web project, you sometimes need to manually read the configuration file under the classpath. Here we will summarize the methods for reading the classpath path and share them with you.
Method 1:
Java code download
- String path = Test. class. getResource ("/"). toString ();
- System. out. println ("path =" + path );
String path = Test.class.getResource("/").toString(); System.out.println("path = " + path);
This method is no problem under tomcat, you can get the WEB-INF/classes path = file:/home/ngidm_db2/AS_Tomcat7_0_29/webapps/NGIDM/WEB-INF/classes/but after weblogic, the obtained path = file:/oracle/weblogic/Oracle/Middleware/Oracle_Home/user_projects/domains/base_domain/is under weblogic, And the classes path cannot be obtained.
Method 2:
Java code
String path2 = Thread. currentThread (). getContextClassLoader (). getResource ("/"). getPath ();
System. out. println ("path2 =" + path2 );
String path2 = Thread.currentThread().getContextClassLoader().getResource("/").getPath(); System.out.println("path2 = " + path2);
Under tomcat and weblogic, you can get the classes path path2 =/oracle/weblogic/Oracle/Middleware/user_apps/NGIDM/WEB-INF/classes/path2 =/home/ngidm_db2/AS_Tomcat7_0_29/webapps/NGIDM /WEB-INF/classes/It is recommended that you use more
Java code
Thread. currentThread (). getContextClassLoader (). getResource ("/"). getPath ();
Thread.currentThread().getContextClassLoader().getResource("/").getPath();
Obtain the classpath path, and the classpath obtained in method 2 does not contain the file: prefix, which can be directly used.