Class类的getResource(String name)方法和ClassLoader的getResource(String name)方法
1、Class.getResource(String name)
package path; import org.junit.Test; import jodd.emial.JoddDemo; public class PathTest { @Test public void pathTest() { System.out.println(JoddDemo.class.getResource(""));//输出file:/E:/workspace/MyDemo/target/classes/jodd/emial/ System.out.println(JoddDemo.class.getResource("/"));//输出file:/E:/workspace/MyDemo/target/test-classes/ } }
由上面程序输出结果可以知道,不加“/”的参数获取的是JoddDemo类所在的包的路径,加“/”的参数获取到的是classpath根目录的路径
package path; import org.junit.Test; import jodd.emial.JoddDemo; public class PathTest { @Test public void pathTest(){ System.out.println(JoddDemo.class.getResource("")); System.out.println(JoddDemo.class.getResource("/")); System.out.println(JoddDemo.class.getClassLoader().getResource("")); System.out.println(JoddDemo.class.getClassLoader().getResource("/")); System.out.println(JoddDemo.class.getResource("/image/dongman1.jpg")); System.out.println(JoddDemo.class.getClassLoader().getResource("/image/dongman1.jpg")); } }
输出结果依次为:
file:/E:/workspace/MyDemo/target/classes/jodd/emial/ file:/E:/workspace/MyDemo/target/test-classes/ file:/E:/workspace/MyDemo/target/test-classes/ null file:/E:/workspace/MyDemo/target/classes/image/dongman1.jpg null