如何在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/