`
huzezhen1
  • 浏览: 7183 次
  • 性别: Icon_minigender_1
  • 来自: 惠州
社区版块
存档分类
最新评论

java读取properties配置文件

阅读更多

java读取properties配置文件(此处以java读取jdbc.properties数据库配置文件为例)

  1. 先创建jdbc.properties文件(此处创建在/WebRoot/WEB-INF/下)
  2. 在java中操作
    String path = Thread.currentThread().getContextClassLoader().getResource("").toString();
    path = path.substring(0,path.lastIndexOf("class")) + "jdbc.properties"; //去掉class\,加上jdbc.properties
    //path=path.replace('/', '\\'); // 将/换成\  
      path=path.replace("file:", ""); //去掉file:  
    //path=path.replace("classes\\", ""); //去掉class\  
      path=path.substring(1); //去掉第一个\,如 \D:\JavaWeb...		
      File jdbc = new File(path);
      if(jdbc.exists()){
    	Properties properties = new Properties();
    	try {
    		properties.load(new FileInputStream(jdbc));
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
            //读取properties配置文件中的url
            url = properties.getProperty("url");
            //读取properties配置文件中的user
            user = properties.getProperty("user"); 
            //读取properties配置文件中的password 
            password = properties.getProperty("password");
      }
     
  3. 在linux下部署时出现读不到此路径的问题,后来发现是
    path=path.substring(1);
     的原因,把它注释掉就可以读到了。就是D:/xxxx....读不到,最前面的'/'不能去掉,即/D:/xxxx....的时候才读取得到。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics