Java擷取絕對路徑一些問題解決方案

來源:互聯網
上載者:User

先看一個執行個體

 代碼如下 複製代碼

// 擷取對象的絕對路徑
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"));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.