很多情況下,我們需要在JavaBean、Servlet中獲得當前的目錄路徑,比如載入設定檔,上傳檔案到伺服器等,這是各種獲得路徑的方法的總結,備忘。
1.載入jdbc.properties
1)ClassLoader的getResourceAsStream("XXX")
InputStream in=XXX.class.getClassLoader().getResourceAsStream("jdbc.properties");
getResourceAsStream()會到classes目錄下找jdbc.properties檔案,所以在工程項目中,我們一般把它放在src目錄下。
2)Class.getResourceAsStream("/XXX")
XXX.class.getResourceAsStream("/jdbc.properties");
兩種方式的共同點就是:jdbc.properties都應該在classes下,也就是項目的src目錄
不同點就是:ClassLoader.getResourceAsStream(“XXX”)中參數不以"/"開頭,而Class.getResourceAsStream("/XXX")終參數以"/"開頭
2.在Javabean中獲得路徑
1)獲得當前類XXX.class檔案的URI目錄,不包括自己:XXX.class.getResource("")
如:在類com.test.XXX中取得項目的根絕對路徑
URL url=XXX.class.getResource("");
String filename=url.getFile();
String projectRootPath=new File(filename,"http://www.cnblogs.com/http://www.cnblogs.com/").getCanonicalPath();
//main函數中測試
//filename:/d:/workspace/testproject/build/calsses/com/test/
//projectRootPath:d:/workspace/testproject
//tomcat中測試
//filename:/d:/tomcat/webapps/testproject/WEB-INF/calsses/com/test/
//projectRootPath:d:/tomcat/webapps/testproject
2)獲得的是當前的classpath的絕對URI路徑:XXX.class.getResource("/")
如:在類com.test.XXX中取得項目的根絕對路徑
URL url=XXX.class.getResource("/");
String filename=url.getFile();
String projectRootPath=new File(filename,"http://www.cnblogs.com/").getCanonicalPath();
//main函數中測試
//filename:/d:/workspace/testproject/build/calsses/
//projectRootPath:d:/workspace/testproject
//tomcat中測試
//filename:/d:/tomcat/webapps/testproject/WEB-INF/calsses/
//projectRootPath:d:/tomcat/webapps/testproject
3)獲得的是當前ClassPath的絕對URI路徑: //推薦使用
Thread.currentThread().getContextClassLoader().getResource("");
4)獲得的是當前ClassPath的絕對URI路徑:
XXX.class.getClassLoader().getResource("");
5)獲得的是當前ClassPath的絕對URI路徑: //推薦使用
ClassLoader.getSystemResource("");
6)目前使用者目錄的相對路徑:System.getProperty("user.dir") //不推薦使用
3.在servlet中獲得路徑
1)獲得相對路徑:
this.getServletContext().getResource("/").getPath();
//輸出:/localhost/testproject/
2)String strPath2=this.getServletContext().getRealPath("/");
//輸出:d:/tomcat/webapps/testproject/