Java obtains the class loading path and the project root path in five ways

Source: Internet
Author: User

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 "));

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.