Java Development Path: Class. getResource and ClassLoader. getResource paths

Source: Internet
Author: User

Java Development Path: Class. getResource and ClassLoader. getResource paths

Class. getResource and ClassLoader. getResource are often used to retrieve resources in Java. When the teacher explained the question yesterday, he asked us why you are all in the front of the document "/":


  1. String path = Resources.class.getResource("/a.txt").getPath();

Note: The a.txt file is created under the resourcesfile.

I think I tried it out, but I don't want to use. To answer questions, let's take a look at the Resources path.

1. Class. getResource (String path)

When the path does not start with '/', resources are retrieved from the package where the class is located by default; when the path starts with '/', resources are obtained from the ClassPath root;

  1. System.out.println("path:"+Resources.class.getResource("/"));
  2. System.out.println("path:"+Resources.class.getResource(""));

Output result:

Path: file:/home/xiaosi/Study/lectures/target/classes/

Path: file:/home/xiaosi/Study/lectures/target/classes/com/qunar/lectures/

 

2. ClassLoder. getClassLoder. getResource (String path)

Path cannot start with '/'; path is obtained from the ClassPath root;

  1. System.out.println(r.getClass().getClassLoader().getResource(""));
  2. System.out.println(r.getClass().getClassLoader().getResource("/"));//null

Output result:

File:/home/xiaosi/Study/lectures/target/classes/

Null

 

 

 

 

 

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.