mongodb.properties 配置文件代码如下
#------------------------mongodb config----------------------------
mongo.host=1.1.1.1
mongo.port=27017
mongo.user=luhailong
mongo.password=luhailong
mongo.dataBaseName=demoDB
properties 配置文件读取类getProperties
package common.mongodb.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.opensymphony.xwork2.util.finder.Test;
/**
* @author luhailong
* @time 2017/8/3
* @Desc properties配置文件读取类
*/
public class getProperties {
/**
* 根据Key读取Value
* @param key 配置文件中的键
* */
public String GetValueByKey(String key) {
Properties pps = new Properties();
try {
InputStream in = Test.class.getClassLoader().getResourceAsStream("mongodb.properties");
pps.load(in);
String value = pps.getProperty(key);
System.out.println(key + " = " + value);
return value;
}catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
实际应用
// 获取配置文件信息
getProperties getPropertiesa = new getProperties();
host = getPropertiesa.GetValueByKey("mongo.host");
port = getPropertiesa.GetValueByKey("mongo.port");
user = getPropertiesa.GetValueByKey("mongo.user");
password = getPropertiesa.GetValueByKey("mongo.password");
dataBaseName = getPropertiesa.GetValueByKey("mongo.dataBaseName");