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
1

 

此外,對於讀寫配置文件,例如properties文件,Java還提供了getResourceAsStream(“文件”)方法返回一個InputStream供讀取文件: 
InputStream is = this.getClass().getClassLoader().getResourceAsStream(“conf.properties”); 


好了,以上也只是一部分方法,還有諸多不足之處,后續補充,歡迎指正!!!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM