Get the path to the Classpath and resource files in the MAVEN project

Source: Internet
Author: User
Tags relative


Assuming that the resource file is placed under the Src/main/resources Resource folder of the MAVEN project, the source file is placed under src/main/java/, then the Java folder and the resources folder are classpath real locations at runtime, if

There is a file located in Src/main/resources/test.txt

There is a class in Src/main/java/com/qunar/myclass.java

file_name = "Test.txt"

By following the code

MyClass.class.getClassLoder (). GetResource (file_name). GetPath ();

You can get the file path directly

Classpath can be obtained by using the following code

MyClass.class.getClassLoder (). GetResource (""). GetPath ();

There is also a way to get the resource address by using the relative path through the load path of the current class

MyClass.class.getResource (file_name). GetPath ()

Then this is problematic because the path at this time is relative to the MyClass class at run time, Test.txt and MyClass are not at one level, because there are two packages before MyClass

Can be resolved as follows

MyClass.class.getResource (File.separator + "file_name"). GetPath (); This method is equivalent to using the absolute run-time path

MyClass.class.getResource (".." + File.separator + ":" + File.separator + file_name). GetPath (); This method is equivalent to using a relative MyClass run-time 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.