如何在java中使用相對路徑?

來源:互聯網
上載者:User
在開發過程中,我們經常會遇到讀取設定檔的情況,對於設定檔的讀取,根據環境等情況又各有不同,一般情況下,如果從非jar包中使用相對/路徑,比較簡單,就不在累述了,而在很多
情況下,我們需要把我們的class打包成jar檔案,進行使用,這時就會發現,我們先前如果沒有考慮到這些,可能就行不通了,那麼,該如何解決呢。方法如下
:
有如下路徑 :
Web-info--|-->classes--->conf-->config.properties
   |-->lib
此時加入我們需要讀取config.properties,在不使用jar包時,使用如下方式讀取,不失為一種方法:
File f = new File(this.getClass().getResource("/").getPath());
f = new File(f.getPath() + "/conf/config.properties");
註:f.getPath()即為當class所在的絕對路徑。如:c:/javasrc/web-inf/classes
然後,對檔案對象進行處理,就能把配置資訊讀取出來了,但是加入如上class被打包成jar檔案,那麼,在程式執行到這裡時,就會無法找到設定檔,那麼該如何處理呢。
處理方法如下:
String s_config="conf/config.properties";
 InputStream in = ClassLoader.getSystemResourceAsStream(s_config);
if( in == null ){
 System.out.println( " 開啟 " + s_config + "失敗。" );
}else
{
Properties properties = new Properties();
properties.load(in);
//
//接下來就可以通過properties.getProperty(String obj)方法對進行配置資訊讀取了
}

作者Blog: http://blog.csdn.net/wjmmml/

聯繫我們

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