idea中项目目录结构
import com.xpp.app.Dog; import java.net.URL; public class Main { public static void main(String[] args) { //当参数不带 / 会默认从该类所在的包下找 URL url1 = Dog.class.getResource(""); //file:/D:/idea_Java_projects/getResource/out/production/getResource/com/xpp/app/ System.out.println(url1); URL url2 = Dog.class.getResource("my.properties"); //null System.out.println(url2); //当参数带 / 会从该类所在的根目录下找 URL url3 = Dog.class.getResource("/"); //file:/D:/idea_Java_projects/getResource/out/production/getResource/ System.out.println(url3); URL url4 = Dog.class.getResource("/my.properties"); //file:/D:/idea_Java_projects/getResource/out/production/getResource/my.properties System.out.println(url4); } }
import com.xpp.app.Dog; import java.net.URL; public class Main { public static void main(String[] args) { //获取类加载器 ClassLoader classLoader = Dog.class.getClassLoader(); //默认从根目录定位资源 URL url1 = classLoader.getResource(""); //file:/D:/idea_Java_projects/getResource/out/production/getResource/ System.out.println(url1); URL url2 = classLoader.getResource("my.properties"); //file:/D:/idea_Java_projects/getResource/out/production/getResource/my.properties System.out.println(url2); //path不能以'/'开头,path是指类加载器的加载范围,在资源加载的过程中,使用的逐级向上委托的形式加载的, // '/'表示Boot ClassLoader类加载器中的加载范围,因为这个类加载器是C++实现的,所以加载范围为null URL url3 = classLoader.getResource("/my.properties"); System.out.println(url3); } }
标签:URL,ClassLoader,getResource,Dog,System,out,Class,加载 From: https://www.cnblogs.com/xpp3/p/18050386