指定文件名读取WEB-INFO目录下properties配置(windows平台)

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

 

public class Config {

 static Logger log = Logger.getLogger(Config.class);
 String cfgFileName = "";

 private Properties properties;

 public Config() {
  properties = new Properties();
 }

 public void load(String filename) {
  try {
   //打开环境配置文件
   FileInputStream fi = new FileInputStream(getWEBINFAddress()+File.separator+ filename);
   //通过properties.load(fi)方面将环境配置文件读入,依次枚举各个环境变量健和值,并配置JVM的环境变量

   properties.load(fi);

   fi.close();

  } catch (IOException ex) {
   log.error(ex);
  } catch (Exception ex) {
   log.error(ex);
  }

 }

 public String getValue(String key) {

  return properties.getProperty(key, "");
 }
 /**
  *
  * @return
  */
 public static String getWEBINFAddress() {
  Class theClass = Config.class;
  java.net.URL u = theClass.getResource("");
  //str会得到这个函数所在类的路径
  String str = u.toString();
  //截去一些前面6个无用的字符
  str = str.substring(6, str.length());
  //将%20换成空格(如果文件夹的名称带有空格的话,会在取得的字符串上变成%20)
  str = str.replaceAll("%20", " ");
  //查找“WEB-INF”在该字符串的位置
  int num = str.indexOf("WEB-INF");
  //截取即可
  str = str.substring(0, num + "WEB-INF".length());
  return str;
 }
}

---------------------datasource.properties配置文件-------------------------

srcDriver=oracle.jdbc.driver.OracleDriver
srcUrl=jdbc:oracle:thin:@192.168.0.3:1521:DB3
srcUsername=×××

srcPassword=×××

---------------------TestConfig.java-----------------------

 public static Test suite() {
  TestSuite suite = new TestSuite("Test for com.linewell.conf");
  //$JUnit-BEGIN$
  Config config=new Config();
  config.load("datasource.properties");
  System.out.println(config.getValue("srcDriver"));
  System.out.println(config.getValue("srcUrl"));
  System.out.println(config.getValue("srcUsername"));
  System.out.println(config.getValue("srcPassword"));
  System.out.println(config.getValue("destDriver"));
  System.out.println(config.getValue("destUrl"));
  System.out.println(config.getValue("destUsername"));
  System.out.println(config.getValue("destPassword"));
  //$JUnit-END$
  return suite;
 }

------------------------------------------------------------------

PS:此版本仅限在window平台,如果为linux则需要修改getWEBINFAddress,在其返回值前面加“//”。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值