在開發Web方面的應用時, 經常需要擷取 伺服器中目前WebRoot的實體路徑。
如果是Servlet , Action , Controller, 或則Filter , Listener , 攔截器等相關類時, 我們隻需要獲得ServletContext, 然後通過ServletContext.getRealPath("/")來擷取目前應用在伺服器上的實體位址。
如果在類中取不到ServletContext時, 有兩種方式可以做到:
1. 利用Java的類加載機制 調用 XXX.class.getClassLoader().getResource(""); 方法來擷取到ClassPath , 然後處理獲得WebRoot目錄,這種方式隻能是該class在WebRoot/WEB-INF/classes下才能生效, 如果該class被打包到一個jar檔案中, 則該方法失效。這時就應該用下面一種方式。
2. spring架構的思路, 在WEB-INF/web.xml中 , 建立一個webAppRootKey的param, 指定一個值(預設為webapp.root)作為鍵值, 然後通過Listener , 或者Filter , 或者Servlet 執行String webAppRootKey = getServletContext().getRealPath("/"); 并将webAppRootKey對應的webapp.root 分别作為Key , Value寫到System Properties系統屬性中。之後在程式中通過System.getProperty("webapp.root")來獲得WebRoot的實體路徑。
根據第二種的思路,我們還可以再擴充一下。不過對于在部署在一台伺服器中的應用來說,若還不是你所需請再往下看。
下面是一些得到classpath和目前類的絕對路徑的一些方法。你可使用其中的一些方法來得到你需要的資源的絕對路徑:
1. DebitNoteAction.class.getResource("")
得到的是目前類FileTest.class檔案的URI目錄。不包括自己!
如:file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/
atacarnet/src/com/evi/modules/atacarnet/action/
2. DebitNoteAction.class.getResource("/")
得到的是目前的classpath的絕對URI路徑。
3. Thread.currentThread().getContextClassLoader().getResource("")
得到的也是目前ClassPath的絕對URI路徑
4. DebitNoteAction.class.getClassLoader().getResource("") 或ClassLoader.getSystemResource("")
得到的也是目前ClassPath的絕對URI路徑。
5. 取得伺服器相對路徑
System.getProperty("user.dir")
例如:E:\apache-tomcat-5.5.16\apache-tomcat-5.5.16\bin
我推薦使用Thread.currentThread().getContextClassLoader().getResource("")來得到目前的classpath的絕對路徑的URI表示法
6. 取得項目中的絕對路徑
一般用request.getRealPath("/")或request.getRealPath("/config/")
但現在不提倡使用request.getRealPath("/")了,大家可試用ServletContext.getRealPath("/")方法得到Web應用程式的根目錄的絕對路徑
要取得src的檔案非常容易,因為src是預設的相對目錄,比如你說要取得src下com目錄的test.java檔案,你隻需要這樣就夠了
File f = new File(com/test.java);
但如果我要取得不在src目錄或者WebRoot目錄下的檔案呢,而是要從src或者WebRoot同級的目錄中取呢,比如說doc吧
我的硬方法是這樣實作的:
String path = this.getServletContext().getRealPath("/");
Properties p = new Properties();
p.load(new FileInputStream(new File(path.substring(0,(path.lastIndexOf("\\WebRoot") + 1)) + "doc/db.properties")));
System.out.println(p.getProperty("driverName"));