`
啸笑天
  • 浏览: 3434911 次
  • 性别: Icon_minigender_1
  • 来自: China
社区版块
存档分类
最新评论

javaweb读取任意目录的下的properties配置文件(解决普通java类读web-inf下任意目录)

 
阅读更多

看到很多用getResourcesAsStream()来读取.properties文件,但是对.properties文件的路径有要求,至少要和包的根目录在同一目录,对于这点,我也是迷糊了好久,就是没有想通,咋个getResourcesAsStream("/var/config.properties") 会返回null,明明文件是在的,就是因为这里的“根目录” 和通常讲的根目录还不一样。
然而,一般,我喜欢把web的配置文件放到WEB-INF里,和web.xml 文件放在一起,如果用getResourcesAsStream()肯定是不行了。
仔细想了一下,找到一个变通的方法:

例如:文件在WEB-INF/url/url.properties。

 

 

 private String readRcErpURL(){
    	  try{
              String url = this.getClass().getResource("").getPath().replaceAll("%20", " ");
              String path = url.substring(0, url.indexOf("WEB-INF")) + "WEB-INF/url/url.properties";
              Properties config = new Properties();
              config.load(new FileInputStream(path));
              return config.getProperty("rcerp.url");
          }
          catch(Exception e){
              e.printStackTrace();
          }
    	  return null;
      }
 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics