Get the Java Project root directory

Source: Internet
Author: User

Acquisition of relative paths

Description: The relative path (that is, who does not specify when it is relative) can be obtained in the following ways (whether it is a generic Java project or a Web project)

String Path = System.getproperty ("User.dir");

E:\github\J2SE

In the relative path above, the files in the Java project are relative to the project's root directory
File paths in Web projects vary depending on the Web server (tomcat is relative to the Tomcat installation directory \ Bin)



The acquisition of a class-loaded directory (that is, when a class of runtime obtains its mount directory)
Common method One (whether it is a generic Java project or a Web project, first navigate to the first level directory where you can see the package path)

String path = GetClass (). getClassLoader (). GetResource ("Logback.xml"). GetPath ();

/e:/github/j2se/target/classes/logback.xml

General Method Two
String path = GetClass (). GetResource ("/logback.xml"). GetPath ();

/e:/github/j2se/target/classes/logback.xml

This method must start with '/'


Access to the Web project root (after publishing)

Request.getrealpath ("/") This method has not been recommended, presumably we have noticed in the process of use.

It is replaced by the following:

String path = Request.getsession (). Getservletcontext (). Getrealpath ("/upload");

E:\Apache-tomcat\apache-tomcat-7.0.53\wtpwebapps\Struts2\upload

String path = Request.getsession (). Getservletcontext (). Getrealpath ("");

E:\Apache-tomcat\apache-tomcat-7.0.53\wtpwebapps\Struts2

Here we have to pay attention to a detail, in which the final path is in the appended state if the new path is placed in the parameter.




Get the Java Project root directory

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.