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 "/":
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;
System.out.println("path:"+Resources.class.getResource("/"));
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;
System.out.println(r.getClass().getClassLoader().getResource(""));
System.out.println(r.getClass().getClassLoader().getResource("/"));//null
Output result:
File:/home/xiaosi/Study/lectures/target/classes/
Null