Java中使用的路徑,分為兩種:絕對路徑和相對路徑。歸根結底,Java本質上只能使用絕對路徑來尋找資源。所有的相對路徑尋找資源的方法,都不過是一些便利方法。不過是API在底層幫助我們構建了絕對路徑,從而找到資源的!
在開發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.
1
|
DebitNoteAction. class .getResource( "" ) |
得到的是當前類FileTest.class文件的URI目錄。不包括自己!
如:
1
|
file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/ |
1
|
atacarnet/src/com/evi/modules/atacarnet/action/ |
2.
1
|
DebitNoteAction. class .getResource( "/" ) |
得到的是當前的classpath的絕對URI路徑。
如:
1
|
file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/ |
3.
1
|
Thread.currentThread().getContextClassLoader().getResource( "" ) |
得到的也是當前ClassPath的絕對URI路徑
如:
1
|
file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/ |
4.
1
|
DebitNoteAction. class .getClassLoader().getResource( "" ) |
或
1
|
ClassLoader.getSystemResource( "" ) |
得到的也是當前ClassPath的絕對URI路徑。
如:
1
|
file:/D:/eclipse/springTest/WebRoot/WEB-INF/classes/ |
5. 取得服務器相對路徑
1
|
System.getProperty( "user.dir" ) |
例如:E:/apache-tomcat-5.5.16/apache-tomcat-5.5.16/bin
我推薦使用Thread.currentThread().getContextClassLoader().getResource("")來得到當前的classpath的絕對路徑的URI表示法
6. 取得項目中的絕對路徑
一般用
1
|
request.getRealPath( "/" ) |
或
1
|
request.getRealPath( "/config/" ) |
但現在不提倡使用request.getRealPath("/")了,大家可試用ServletContext.getRealPath("/")方法得到Web應用程序的根目錄的絕對路徑
要取得src的文件非常容易,因為src是默認的相對目錄,比如你說要取得src下com目錄的test.java文件,你只需要這樣就夠了
1
|
File f = new File(com/test.java); |
但如果我要取得不在src目錄或者WebRoot目錄下的文件呢,而是要從src或者WebRoot同級的目錄中取呢,比如說doc吧
我的硬方法是這樣實現的:
1
2
3
4
5
6
7
|
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" )); |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/c5153000/article/details/6272195