JAVA擷取檔案本身所在的磁碟位置

來源:互聯網
上載者:User

我們在做java開發(純java程式,或者java web開發)時,經常會遇到需要讀取設定檔的需求,如果我們將檔案所在位置的資訊直接寫到程式中,例如:E:\workspace\JavaGUI\bin\com\util這個目錄,這樣雖然可行,但是,卻產生了很大的局限性,因為讀取的檔案必須要要滿足在E:\workspace\JavaGUI\bin\com\util之下才能夠被正常讀取,否則java拋異常。那如果在沒有E盤盤符的伺服器上,這樣的程式是沒辦法執行的。所以就需要我們的程式能夠讀取當前檔案的所在位置,從而確定檔案的物理磁碟位置,而不是手動寫入這個位置。

以下程式,就實現了這個功能

/**

* 得到類的路徑,例如E:\workspace\JavaGUI\bin\com\util

* @return

* @throws java.lang.Exception

*/

public String getClassPath() throws Exception {

try {

String strClassName = getClass().getName();

String strPackageName = "";

if (getClass().getPackage() != null) {

strPackageName = getClass().getPackage().getName();

}

String strClassFileName = "";

if (!"".equals(strPackageName)) {

strClassFileName = strClassName.substring(strPackageName.length() + 1,

strClassName.length());

} else {

strClassFileName = strClassName;

}

URL url = null;

url = getClass().getResource(strClassFileName + ".class");

String strURL = url.toString();

strURL = strURL.substring(strURL.indexOf('/') + 1, strURL

.lastIndexOf('/'));

//返回當前類的路徑,並且處理路徑中的空格,因為在路徑中出現的空格如果不處理的話,

//在訪問時就會從空格處斷開,那麼也就取不到完整的資訊了,這個問題在web開發中尤其要注意

return strURL.replaceAll("%20", " ");

} catch (Exception ex) {

ex.printStackTrace();

throw ex;

}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.