java获取Resources目录文件问题
2018-10-06 本文已影响0人
holyABCD
问题
为什么resource1能获取到,而resource获取不到呢?
目录结构
-java
- com.xxx
-YmlTest.java
- resources
application.yml
YmlTest.java代码
public class YmlTest {
public static void main(String[] args){
Yaml yaml = new Yaml();
//下面两个获取的都是YmlTest本身所在的classloader
URL resource = YmlTest.class.getResource("application.yml");
URL resource1 = YmlTest.class.getClassLoader().getResource("application.yml");
}
}
问题解决
查看Class代码
public java.net.URL getResource(String name) {
//这里会把传入的名称,update成当前类 包名 + "/" + name
name = resolveName(name);
ClassLoader cl = getClassLoader0();
if (cl==null) {
// A system class.
return ClassLoader.getSystemResource(name);
}
return cl.getResource(name);
}
public URL getResource(String name) {
URL url;
if (parent != null) {
url = parent.getResource(name);
} else {
url = getBootstrapResource(name);
}
if (url == null) {
url = findResource(name);
}
return url;
}