欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-08 12:04:04
...
看到很多用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;  
         }  


下面四种方式都可以得到webroot/WEB-INF/classes这个路径,有什么区别,哪种方式最好?
String path = this.getClass().getResource("/").getPath();
String path2 = this.getClass().getClassLoader().getResource("/").getPath();
String path3 = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String path4 = pageContext.getServletContext().getRealPath("/")+ "/WEB-INF/classes/ ;

个人认为第三种
第一种有线程安全问题
第二种在liunx下不能用是因为liunx不是用“/”而是用“/”所以没有跨平台性
第四种使用起来不够灵活配置文件不能移动到其它文件夹下
相关标签: java