Java GetResource two ways to use

Source: Internet
Author: User
Tags svn

1. Create a new Java project;

2, a new test package under the Src/main/java;

3. Create a new Test.java file and file.txt file under the test package;

4, Test.java file content is written as follows:

 Package test; Import Java.net.URL;  Public class Test {    publicstaticvoid  main (string[] args) {        = Test. class. GetResource ("file.txt");        System.out.println (URL);         = Thread.CurrentThread (). Getcontextclassloader (). GetResource ("Test/file.txt");        System.out.println (URL);}    }  

The print result is the absolute path to the file.txt file, as follows:

file:/users/lay-mac/desktop/svn/ali-mine/web/chapter3/target/classes/test/file.txtfile:/Users/lay-mac /desktop/svn/ali-mine/web/chapter3/target/classes/test/file.txt

We have seen the two methods of calling GetResource:

1) Class Call

This method of invocation can be understood as relative to the location of the Test.class file

file:/users/lay-mac/desktop/svn/ali-mine/web/chapter3/target/classes/test/

Stitching on

File.txt

2) ClassLoader Call

The class loader invocation method can be understood as relative to the location of the classpath:

file:/users/lay-mac/desktop/svn/ali-mine/web/chapter3/target/classes/

Stitching on

Test/file.txt

Note: Both file.txt and text/file.txt cannot be preceded by "/", which will not be found to return null

Java GetResource two ways to use

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.