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,在其返回值前面加“//”。