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;
}
原文地址:https://www.cnblogs.com/fenglie/p/3850196.html