我的Java開發學習之旅——>JAVA 筆記ClassLoader.getResourceAsStream() 與 Class.getResourceAsStream()

來源:互聯網
上載者:User

今天,一讀者在我的 Android通過調用Webservice實現手機號碼歸屬地查詢 文章中給我回複了一個問題,由於沒有具體說明我的sop12.xml檔案是放在src目錄下,不是和具體操作類AddressService.java放在同一目錄下,引起了誤會。


  1. InputStream inputStream = AddressService.class.getClassLoader()  
  2.                 .getResourceAsStream("sop12.xml");
     




現在在這裡總結一下Java中getResourceAsStream的用法。

首先,Java中的getResourceAsStream有以下幾種:
1. Class.getResourceAsStream(String path) : path 不以’/'開頭時預設是從此類所在的包下取資源,以’/'開頭則是從

ClassPath根下擷取。其只是通過path構造一個絕對路徑,最終還是由ClassLoader擷取資源。

2. Class.getClassLoader.getResourceAsStream(String path) :預設則是從ClassPath根下擷取,path不能以’/'開頭,最終是由

ClassLoader擷取資源。

3. ServletContext. getResourceAsStream(String path):預設從WebAPP根目錄下取資源,Tomcat下path是否以’/'開頭無所謂,

當然這和具體的容器實現有關。

4. Jsp下的application內建對象就是上面的ServletContext的一種實現。

其次,getResourceAsStream 用法大致有以下幾種:

第一: 要載入的檔案和.class檔案在同一目錄下,例如:com.x.y 下有類me.class ,同時有資源檔myfile.xml

那麼,應該有如下代碼:

me.class.getResourceAsStream("myfile.xml");

第二:在me.class目錄的子目錄下,例如:com.x.y 下有類me.class ,同時在 com.x.y.file 目錄下有資源檔myfile.xml

那麼,應該有如下代碼:

me.class.getResourceAsStream("file/myfile.xml");

第三:不在me.class目錄下,也不在子目錄下,例如:com.x.y 下有類me.class ,同時在 com.x.file 目錄下有資源檔myfile.xml

那麼,應該有如下代碼:

me.class.getResourceAsStream("/com/x/file/myfile.xml");

總結一下,可能只是兩種寫法

第一:前面有 “ / ”

“ / ”代表了工程的根目錄,例如工程名叫做myproject,“ / ”代表了myproject

me.class.getResourceAsStream("/com/x/file/myfile.xml");

第二:前面沒有 “ / ”

代表當前類的目錄

me.class.getResourceAsStream("myfile.xml");

me.class.getResourceAsStream("file/myfile.xml"); 

最後,自己的理解: 
getResourceAsStream讀取的檔案路徑只局限與工程的源檔案夾中,包括在工程src根目錄下,以及類包裡面任何位置,但是如果設定檔路徑是在除了源檔案夾之外的其他檔案夾中時,該方法是用不了的。 




附註:java.lang.ClassLoader.gClassLoader()源碼

 /**     * Returns an input stream for reading the specified resource.     *     * <p> The search order is described in the documentation for {@link     * #getResource(String)}.  </p>     *     * @param  name     *         The resource name     *     * @return  An input stream for reading the resource, or <tt>null</tt>     *          if the resource could not be found     *     * @since  1.1     */    public InputStream getResourceAsStream(String name) {URL url = getResource(name);try {    return url != null ? url.openStream() : null;} catch (IOException e) {    return null;}    }

java.lang.ClassLoader.getResource()源碼

/**     * Finds the resource with the given name.  A resource is some data     * (images, audio, text, etc) that can be accessed by class code in a way     * that is independent of the location of the code.     *     * <p> The name of a resource is a '<tt>/</tt>'-separated path name that     * identifies the resource.     *     * <p> This method will first search the parent class loader for the     * resource; if the parent is <tt>null</tt> the path of the class loader     * built-in to the virtual machine is searched.  That failing, this method     * will invoke {@link #findResource(String)} to find the resource.  </p>     *     * @param  name     *         The resource name     *     * @return  A <tt>URL</tt> object for reading the resource, or     *          <tt>null</tt> if the resource could not be found or the invoker     *          doesn't have adequate  privileges to get the resource.     *     * @since  1.1     */    public URL getResource(String name) {URL url;if (parent != null) {    url = parent.getResource(name);} else {    url = getBootstrapResource(name);}if (url == null) {    url = findResource(name);}return url;    }

java.lang.Class.getResourceAsStream(String name)源碼

/**     * Finds a resource with a given name.  The rules for searching resources     * associated with a given class are implemented by the defining     * {@linkplain ClassLoader class loader} of the class.  This method     * delegates to this object's class loader.  If this object was loaded by     * the bootstrap class loader, the method delegates to {@link     * ClassLoader#getSystemResourceAsStream}.     *     * <p> Before delegation, an absolute resource name is constructed from the     * given resource name using this algorithm:     *     * <ul>     *     * <li> If the <tt>name</tt> begins with a <tt>'/'</tt>     * (<tt>'\u002f'</tt>), then the absolute name of the resource is the     * portion of the <tt>name</tt> following the <tt>'/'</tt>.      *     * <li> Otherwise, the absolute name is of the following form:     *     * <blockquote><pre>     *   <tt>modified_package_name</tt>/<tt>name</tt>     * </pre></blockquote>     *     * <p> Where the <tt>modified_package_name</tt> is the package name of this     * object with <tt>'/'</tt> substituted for <tt>'.'</tt>     * (<tt>'\u002e'</tt>).     *     * </ul>     *     * @param  name name of the desired resource     * @return      A {@link java.io.InputStream} object or <tt>null</tt> if     *              no resource with this name is found     * @throws  NullPointerException If <tt>name</tt> is <tt>null</tt>     * @since  JDK1.1     */     public InputStream getResourceAsStream(String name) {        name = resolveName(name);        ClassLoader cl = getClassLoader0();        if (cl==null) {            // A system class.            return ClassLoader.getSystemResourceAsStream(name);        }        return cl.getResourceAsStream(name);    }


java.lang.Class.getResource(String
name)源碼

/**     * Finds a resource with a given name.  The rules for searching resources     * associated with a given class are implemented by the defining     * {@linkplain ClassLoader class loader} of the class.  This method     * delegates to this object's class loader.  If this object was loaded by     * the bootstrap class loader, the method delegates to {@link     * ClassLoader#getSystemResource}.     *     * <p> Before delegation, an absolute resource name is constructed from the     * given resource name using this algorithm:     *     * <ul>     *     * <li> If the <tt>name</tt> begins with a <tt>'/'</tt>     * (<tt>'\u002f'</tt>), then the absolute name of the resource is the     * portion of the <tt>name</tt> following the <tt>'/'</tt>.      *     * <li> Otherwise, the absolute name is of the following form:     *     * <blockquote><pre>     *   <tt>modified_package_name</tt>/<tt>name</tt>     * </pre></blockquote>     *     * <p> Where the <tt>modified_package_name</tt> is the package name of this     * object with <tt>'/'</tt> substituted for <tt>'.'</tt>     * (<tt>'\u002e'</tt>).     *     * </ul>     *     * @param  name name of the desired resource     * @return      A  {@link java.net.URL} object or <tt>null</tt> if no     *              resource with this name is found     * @since  JDK1.1     */    public java.net.URL getResource(String name) {        name = resolveName(name);        ClassLoader cl = getClassLoader0();        if (cl==null) {            // A system class.            return ClassLoader.getSystemResource(name);        }        return cl.getResource(name);    }

從中可以看得出來:Class.getResource()和Class.getResourceAsStream()方法

尋找與給定類相關的資源的規則是通過定義類的class loader 實現的。此方法委託此對象的類載入器。如果此對象通過引導類載入器載入,則此方法將委託給 ClassLoader.getSystemResourceAsStream(java.lang.String)。和 ClassLoader.getSystemResource(java.lang.String)
 

在委託前,使用下面的演算法從給定的資源名構造一個絕對資源名:

  • 如果 name 以 '/' 開始 ('\u002f'),則絕對資源名是 '/' 後面的name 的一部分。
  • 否則,絕對名具有以下形式:
       modified_package_name/name

    其中 modified_package_name 是此對象的包名,該名用 '/' 取代了 '.' ('\u002e')。

 

==================================================================================================

  作者:歐陽鵬  歡迎轉載,與人分享是進步的源泉!

  轉載請保留原文地址:http://blog.csdn.net/ouyang_peng

==================================================================================================

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.