getResourcesAsStream()來讀取.properties文件,但是getResourcesAsStream()僅在java項目時能獲取根目錄的文件;
在web項目中,getResourcesAsStream()是獲取classes目錄的根路徑
例如:文件在WEB-INF/conf/conf.properties。
private Properties readConf(){
InputStream is = null;
try{
//獲取classes的路徑,注意:由於轉碼的原因需要將%20(空格轉碼后的字符)替換為空格 String classesUrl = this.getClass().getResource("").getPath().replaceAll("%20", " ");
//獲取web項目的根路徑,拼接文件路徑 String filePath = classesUrl.substring(0, classesUrl.indexOf("WEB-INF")) + "WEB-INF/xxx/xxx.properties";
//讀取 Properties p = new Properties();
is = new FileInputStream(filePath);
p.load(is);
return p;
} catch(IOException e){
e.printStackTrace();
} finally{
try{
if(is !=null){
is.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}