1. 程式人生 > >Class.getResources()和classLoader.getResources()區別

Class.getResources()和classLoader.getResources()區別

ace 怎麽 資源 works ID .com print sun rop

Class.getResource(String path)

path不以’/‘開頭時,默認是從此類所在的包下取資源;
path  以’/‘開頭時,則是從ClassPath根下獲取;

技術分享圖片
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/

如果我們想在TestMain.java中分別取到1~3.properties文件,該怎麽寫路徑呢?代碼如下:

package testpackage;

public class TestMain {

    public static void main(String[] args) {
        // 當前類(class)所在的包目錄
        System.out.println(TestMain.class.getResource(""));
        
// class path根目錄 System.out.println(TestMain.class.getResource("/")); // TestMain.class在<bin>/testpackage包中 // 2.properties 在<bin>/testpackage包中 System.out.println(TestMain.class.getResource("2.properties")); // TestMain.class在<bin>/testpackage包中
// 3.properties 在<bin>/testpackage.subpackage包中 System.out.println(TestMain.class.getResource("subpackage/3.properties")); // TestMain.class在<bin>/testpackage包中 // 1.properties 在bin目錄(class根目錄) System.out.println(TestMain.class.getResource("/1.properties")); } }

Class.getClassLoader().getResource(String path)

path不能以’/‘開頭時;
path是從ClassPath根下獲取;
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
    }
}

輸出結果

class testpackage.TestMain
sun.misc.Launcher$AppClassLoader@1fb8ee3
file:/E:/workspace/Test/bin/
null

使用Class.getClassLoader().getResource(String path)可以這麽寫

package testpackage;

public class TestMain {
    public static void main(String[] args) {
        TestMain t = new TestMain();
        System.out.println(t.getClass().getClassLoader().getResource(""));
        
        System.out.println(t.getClass().getClassLoader().getResource("1.properties"));
        System.out.println(t.getClass().getClassLoader().getResource("testpackage/2.properties"));
        System.out.println(t.getClass().getClassLoader().getResource("testpackage/subpackage/3.properties"));
    }
}

From:http://www.cnblogs.com/yejg1212/p/3270152.html

Class.getResources()和classLoader.getResources()區別