這兩個getResource()是使用當前ClassLoader加載資源(即資源在 Class path中),這樣資源和class直接打在jar包中,避免文件路徑問題. spa
二者不一樣是Class的getResource()方法是從當前.class文件路徑查找資源,ClassLoader則是從jar包根目錄查找. code
Class.getResource(String path)
path不以’/'開頭時,默認是今後類所在的包下取資源;
path 以’/'開頭時,則是從ClassPath根下獲取;ip
package testpackage; public class TestMain { public static void main(String[] args) { System.out.println(TestMain.class.getResource("")); System.out.println(TestMain.class.getResource("/")); } }
輸出結果:資源
file:/E:/workspace/Test/bin/testpackage/ file:/E:/workspace/Test/bin/
上面說到的【path以’/'開頭時,則是從ClassPath根下獲取;】在這裏就是至關於bin目錄(Eclipse環境下)。get
Class.getClassLoader().getResource(String path)
path不能以’/'開頭時;
path是從ClassPath根下獲取;class
package testpackage; public class TestMain { public static void main(String[] args) { TestMain t = new TestMain(); System.out.println(t.getClass()); System.out.println(t.getClass().getClassLoader()); System.out.println(t.getClass().getClassLoader().getResource("")); System.out.println(t.getClass().getClassLoader().getResource("/"));//null } }
輸出結果:test
class testpackage.TestMain sun.misc.Launcher$AppClassLoader@1fb8ee3 file:/E:/workspace/Test/bin/ null
一樣效果cli
com.explorers.Test.class.getResourceAsStream("abc.jpg")
= com.explorers.Test.class.getResourceAsStream("/com/explorers/abc.jpg")
= ClassLoader.getResourceAsStream("com/explorers/abc.jpg")file