Java - 獲取ClassPath的路徑和資源

襲冷發表於2014-05-25

一、說明

    ClassLoader 提供了兩個方法用於取得裝載的類路徑和取得其中的資源:

        public URL getResource (String name);  //得到的一個URL物件來定位資源

        public InputStream getResourceAsStream (String name);  //取得該資源輸入流的引用

    注意:這裡name是資源相對於類的路徑,即相對於"/"根路徑下的位置


二、示例

    1、獲取當前class檔案所在位置的絕對路徑

        程式碼:this.getClass().getResource("").getPath(); 

        結果:/D:/Works/JavaTest/PathTest/bin/com/xilen/test


    2、獲取classpath的絕對路徑

        程式碼:this.getClass().getResource("/").getPath();

        結果:/D:/JWorks/JavaTest/PathTest/bin/


    3、通過執行緒的方式獲取classpath的絕對路徑

        程式碼:Thread.currentThread().getContextClassLoader().getResource("").getPath();

        結果:/D:/Works/JavaTest/PathTest/bin/


    4、通過ClassLoader的靜態方法獲取classpath的絕對路徑

        程式碼:ClassLoader.getSystemResource("").getPath();

        結果:/D:/Works/JavaTest/PathTest/bin/


    5、補充:得到Web應用程式的根目錄的絕對路徑

        程式碼:ServletActionContext.getServletContext().getRealPath(“/”);

        結果:/D:/Server/apache-tomcat-7.0.42/webapps/WebTest


三、注意

    1、getResource()和getResourceAsStream()是成對出現的

    2、經過ClassLoader獲取的預設已經是根路徑,不能再傳入"/"引數

 

 

 

相關文章