1. 程式人生 > >關於java普通類怎樣獲取當前的WebRoot目錄。

關於java普通類怎樣獲取當前的WebRoot目錄。

前陣子公司安排去另一個專案組幫忙,其中用到了FCKeditor。FCKeditor我們都知道,是一款不錯的上傳下載的外掛,由於剛剛接觸FCKeditor,而且之前開發人員由於一些原因離職,所以我開始慢慢的探索FCKeditor。其中要求FCKeditor的檔案儲存目錄隨著專案變化而變化,即不是寫死為一個固定硬碟路徑。可悲的我連路徑也找不到,到了最後終於找到了,卻不知道怎麼改。於是自己參考網上一個例子,整理了一個java類獲取WebRoot目錄方法,供大家使用。

public String getWebInfPath(String index4Str) { URL url = getClass().getProtectionDomain().getCodeSource() .getLocation(); String path = url.toString(); int index = path.indexOf(index4Str); if (index == -1) { index = path.indexOf("WEB-INF"); } if (index == -1) { index = path.indexOf("bin"); } path = path.substring(0, index); if (path.startsWith("zip")) {// 當class檔案在war中時,此時返回zip:D:/...這樣的路徑 path = path.substring(4); } else if (path.startsWith("file")) {// 當class檔案在class檔案中時,此時返回file:/D:/...這樣的路徑 path = path.substring(6); } else if (path.startsWith("jar")) {// 當class檔案在jar檔案裡面時,此時返回jar:file:/D:/...這樣的路徑 path = path.substring(10); } try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return path; }