java中獲得項目的src文件夾的路徑


在java中獲得文件的路徑在我們做上傳文件操作時是不可避免的。

web 上運行
1:this.getClass().getClassLoader().getResource("/").getPath();
this.getClass().getClassLoader().getResource("").getPath(); 得到的是 ClassPath的絕對URI路徑。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/
System.getProperty("user.dir");
this.getClass().getClassLoader().getResource(".").getPath(); 得到的是 項目的絕對路徑
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war

2:this.getClass().getResource("/").getPath();
this.getClass().getResource("").getPath(); 得到的是當前類 文件的URI目錄。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/com/jebel/helper/
this.getClass().getResource(".").getPath(); X 不 能運行

3:Thread.currentThread().getContextClassLoader().getResource("/").getPath()
Thread.currentThread().getContextClassLoader().getResource("").getPath() 得到的是 ClassPath的絕對URI路徑。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/
Thread.currentThread().getContextClassLoader().getResource(".").getPath() 得到的是 項目的絕對路徑
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war

在本地運行中
1:this.getClass().getClassLoader().getResource("").getPath();
this.getClass().getClassLoader().getResource(".").getPath(); 得到的是 ClassPath的絕對URI路徑。
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes
this.getClass().getClassLoader().getResource(".").getPath(); X 不 能運行
2:this.getClass().getResource("").getPath();
this.getClass().getResource(".").getPath(); 得到的是當前類 文件的URI目錄。
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes/com/jebel/helper/
/D:/myProjects/hp/WebRoot/WEB-INF/classes/ 得到的是 ClassPath的絕對URI路徑。
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes

3:Thread.currentThread().getContextClassLoader().getResource(".").getPath()
Thread.currentThread().getContextClassLoader().getResource("").getPath() 得到的是 ClassPath的絕對URI路徑。。
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes
Thread.currentThread().getContextClassLoader().getResource("/").getPath() X 不 能運行

最后
Web應用程序中,我們一般通過ServletContext.getRealPath("/")方法得到Web應用程序根目錄絕對路徑
還有request.getContextPath(); 在Weblogic中要用request.getServletContext().getContextPath();但如果打包成war部署到Weblogic服務器,項目內部並沒有文件結構的概念,用這種方式是始終得到null,獲取不到路徑,目前還沒有找到具體的解決方案


免責聲明!

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



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