先看一個執行個體
| 代碼如下 |
複製代碼 |
// 擷取對象的絕對路徑 public static String realpath(Object obj) throws URISyntaxException { return new File(obj.getClass().getResource("").toURI()).getAbsolutePath(); } |
一般情況下不需要直接使用絕對路徑,使用流就可以了,this.getClass().getResourceAsStream(filename)。
如果要擷取項目的根路徑,把代碼中obj.getClass()換成obj.getClass().getClassLoader()就可以了。
System.getProperty(“user.dir”) 使用者的當前工作目錄,這個應該和環境有關係,在eclipse中是src的上層目錄。
其他資訊自己看JDK API就明白了。
| 代碼如下 |
複製代碼 |
/** * 對象所在目錄的絕對路徑,也就是包的絕對路徑 * * @param obj * Object * * @return String */ public static String getClassPath(Object obj) throws URISyntaxException { return new File(obj.getClass().getResource("").toURI()) .getAbsolutePath(); } /** * 擷取當前項目的根路徑(絕對路徑) * * @param obj * Object * * @return String */ public static String getProjectPath(Object obj) throws URISyntaxException { return new File(obj.getClass().getClassLoader().getResource("").toURI()) .getAbsolutePath(); } |
如果我一個在取得項目中的絕對路徑
一般用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")); |