Java class.getClassLoader().getResource("")獲取資源路徑

在開發中經常需要獲取資源文件路徑,例如讀寫配置文件等。Java也提供很多方法來獲取這些路徑,下面就幾種常用到的作一下討論區分:
1、xxx.class.getClassLoader().getResource(“”).getPath();
獲取src資源文件編譯後的路徑(即classes路徑)
2、xxx.class.getClassLoader().getResource(“文件”).getPath();
獲取classes路徑下“文件”的路徑
3、xxx.class.getResource(“”).getPath();
缺少類加載器,獲取xxx類經編譯後的xxx.class路徑
4、this.getClass().getClassLoader().getResource(“”).getPath();
以上三種方法的另外一種寫法
5、request().getSession().getServletContext().getRealPath(“”);
獲取web項目的路徑
例如:

System.out.println(FileUpLoadAction.class.getClassLoader().getResource("conf.properties").getPath());
            System.out.println(FileUpLoadAction.class.getClassLoader().getResource("").getPath());
            System.out.println(FileUpLoadAction.class.getResource("").getPath());
            System.out.println(this.getClass().getClassLoader().getResource("").getPath());
            System.out.println(ServletActionContext.getRequest().getSession().getServletContext().getRealPath("login.jsp"));

輸出依次爲:

/D:/codes/trunk/client/web/IBMS/myworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/webclient/WEB-INF/classes/conf.properties
/D:/codes/trunk/client/web/IBMS/myworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/webclient/WEB-INF/classes/
/D:/codes/trunk/client/web/IBMS/myworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/webclient/WEB-INF/classes/com/gmi/client/
/D:/codes/trunk/client/web/IBMS/myworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/webclient/WEB-INF/classes/
D:\codes\trunk\client\web\IBMS\myworkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\webclient\login.jsp

此外,對於讀寫配置文件,例如properties文件,Java還提供了getResourceAsStream(“文件”)方法返回一個InputStream供讀取文件:
InputStream is = this.getClass().getClassLoader().getResourceAsStream(“conf.properties”);
好了,以上也只是一部分方法,還有諸多不足之處,後續補充,歡迎指正!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章