Copy codeThe Code is as follows: package my;
Import java. io. File;
Import java. io. IOException;
Import java.net. URL;
Public class MyUrlDemo {
Public static void main (String [] args ){
MyUrlDemo muDemo = new MyUrlDemo ();
Try {
MuDemo. showURL ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
Public void showURL () throws IOException {
// Method 1: Obtain the root path D: \ git \ daotie \ target \ classes for class loading
File f = new File (this. getClass (). getResource ("/"). getPath ());
System. out. println (f );
// Obtain the project path of the current class. If "/" is not added, obtain the loading Directory D: \ git \ daotie \ target \ classes \ my of the current class.
File f2 = new File (this. getClass (). getResource (""). getPath ());
System. out. println (f2 );
// Method 2: Obtain the project path D: \ git \ daotie
File directory = new File (""); // The parameter is null.
String courseFile = directory. getCanonicalPath ();
System. out. println (courseFile );
// File:/D:/git/daotie/target/classes/
URL xmlpath = this. getClass (). getClassLoader (). getResource ("");
System. out. println (xmlpath );
// Category 4: D: \ git \ daotie
System. out. println (System. getProperty ("user. dir "));
/*
* Result: C: \ Documents ents and Settings \ Administrator \ workspace \ projectName
* Get the current project path
*/
// Method 5: obtain all the class paths, including the jar package paths
System. out. println (System. getProperty ("java. class. path "));
}
}