class getResourceAsStream 和 classloader getResourceAsStream獲取資源的不一樣

工程目錄結構:java

prj(工程根目錄)json

  cnspa

    jsoncode

      classloaderxml

        GetResourceByClassAndClassLoader.Javablog

  beans.xmlssl

  

/**
 *
 */
package cn.json.classloader;

import java.io.InputStream;

/**
 * @author json
 * 
 * @date 2014-5-7
 * 
 * @version 1.0
 */
public class GetResourceByClassAndClassLoader {

    /**
     * class 獲取資源是相對於當前class所在路徑去獲取
     * 
     * classloader 是相對於classpath去獲取相應的資源,採用絕對路徑
     * 
     * @param args
     */
    public static void main(String[] args) {
        GetResourceByClassAndClassLoader bean = new GetResourceByClassAndClassLoader();
        InputStream is = bean.getClass().getResourceAsStream("../../../beans.xml");
        if (is == null) {
            System.out.println("resources not found!");
        }
        is = null;
        is = bean.getClass().getResourceAsStream("/beans.xml");
        if (is == null) {
            System.out.println("resources not found!");
        }
        is = null;
        is = bean.getClass().getClassLoader().getResourceAsStream("beans.xml");
        if (is == null) {
            System.out.println("resources not found!");
        }
    }
}
相關文章
相關標籤/搜索