Obtain the resource file in the classpath path in Java

Source: Internet
Author: User
Classloader provides two methods for obtaining resources from the loaded class path:

Public URL getresource (string name );
Public inputstream getresourceasstream (string name );

Here name is the class path of the resource, which is relative to the location under the "/" root path. Getresource obtains a URL object to locate the resource, while getresourceasstream obtains the reference guarantee of the resource input stream.ProgramData can be extracted from the correct location.

But when I call these two methods for the first time, I fail to get the resources I want. In the past, we used not the classloader methods, but the getresource and getresourceasstream methods of the class, because the class object can be obtained from your class (such as yourclass. class or yourclass. getclass (), while classloader needs to call yourclass again. the getclassloader () method, but according to the JDK documentation, the two methods of the class object are actually "delegated" (delegate) to the classloader that loads it, therefore, you only need to use the two methods of the Class Object.

Conclusion: call this. getclass. getresourceasstream (string name) to obtain a positive solution.

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.