当前位置: 首页 > Java教程 > 正文

普通Java类读取WEB-INF目录下的jdbc.properties属性文件

收藏文章Loading
收藏
(82)

今天更改一个项目的部分功能,需要读取WEB-INF目录下的jdbc.properties文件,但是当运行时候却出现IO读取异常,说系统找不到路径,但是查看文件目录结构是正确的。那么,只能是路径问题,网上查询资料获得了解决办法,大体思路是获得当前类的绝对路径然后截取字符串得到WEB-INF路径然后拼接,具体实例代码如下:

try{  
    //获得当前类的绝对路径
    //replaceAll("%20", "")这个替换是因为据说getPath()读取时会把空格读取为“%20”
    String url = this.getClass().getResource("/").getPath()
                                                 .replaceAll("%20", ""); 
    //截取字符串得到WEB-INF路径然后拼接
    String path = url.substring(0, url.indexOf("WEB-INF")) + 
                  "WEB-INF/config/jdbc.properties";  
    
    Properties properties = new Properties();  
    properties.load(new FileInputStream(path));  
    //获得属性文件中的jdbc.username
    String dbUser = properties.getProperty("jdbc.username");
}catch(Exception e){  
    e.printStackTrace();  
} 

经测试以上这段代码的确可以正确的读取到jdbc.properties属性文件,但是会经过大量的字符串拼接操作,代码不太直观。相对来说,Csyor还是比较喜欢下面这种方法,但是我这网上看到有的网友说不提倡使用,这里就仁者见仁智者见智吧。

try{  
    //直接获得WEB-INF/config/jdbc.properties的绝对路径
    String path = getServletContext()
                           .getRealPath("WEB-INF/config/jdbc.properties");
		
    Properties properties = new Properties();
    properties.load(new FileInputStream(new File(path))); 
    
    //获得属性文件中的jdbc.username
    String dbUser = properties.getProperty("jdbc.username");
}catch(Exception e){  
    e.printStackTrace();  
} 

本文固定链接: http://www.csyor.com/756.html - 穿梭于偶然

该日志由 Csyor 于2014年05月13日发表在 Java教程 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: 普通Java类读取WEB-INF目录下的jdbc.properties属性文件 - 穿梭于偶然
关键字: , , ,

普通Java类读取WEB-INF目录下的jdbc.properties属性文件:目前有3 条留言

  1. There are actually a variety of particulars like that to take into consideration. That is a great level to deliver up. I provide the ideas above as general inspiration but clearly there are questions just like the one you carry up where a very powerful factor can be working in honest good faith. I don?t know if best practices have emerged around things like that, however I’m certain that your job is clearly recognized as a good game. Each girls and boys really feel the impression of only a second抯 pleasure, for the rest of their lives.

    2020-09-28 14:11 [回复]
  2. 沙发
    jordan retro:

    There are actually lots of details like that to take into consideration. That could be a nice level to bring up. I provide the ideas above as general inspiration but clearly there are questions like the one you bring up where a very powerful factor shall be working in trustworthy good faith. I don?t know if best practices have emerged round issues like that, but I’m certain that your job is clearly recognized as a good game. Both boys and girls feel the influence of only a second抯 pleasure, for the rest of their lives.

    2020-09-26 12:43 [回复]

发表评论


快捷键:Ctrl+Enter