java getResourcesAsStream()如何獲取WEB-INF下的文件流


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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM