当前位置: 代码迷 >> Web前端 >> javaweb读取任意目录的上的properties配置文件(解决普通java类读web-inf上任意目录)
  详细解决方案

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

热度:392   发布时间:2012-10-20 14:12:47.0
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;
      }
?

?

?

?

?

?

?

?

?

  相关解决方案