您的位置:首页 > 编程语言 > Java开发

使用java系统属性user.dir读取配置文件

2018-08-03 14:26 821 查看

适用于windows和linux服务器读取配置文件

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

import org.apache.log4j.Logger;

public final class PropertyUtil {
private static Logger LOG = Logger.getLogger(PropertyUtil.class);

// 配置文件
private static Properties demoProps = new Properties();
// 单例模式
private static PropertyUtil instance = null;

private PropertyUtil() {
// user.dir为应用目录
String filePath = System.getProperty("user.dir") + File.separator
+ "WEB-INF" + File.separator + "classes" + File.separator
+ "resources" + File.separator;
LOG.info(filePath);
try {
File demoFile = new File(filePath + "demo.properties");

if (httpFile.exists()) {
demoProps.load(new FileInputStream(filePath
+ "demo.properties"));
}

} catch (IOException e) {
LOG.info("The Exception occured.", e);
}
}

public synchronized static PropertyUtil getInstance() {
if (null == instance) {
instance = new PropertyUtil();
}

return instance;
}

/**
* 获取参数值
*
* @param key
*            properites的key值
* @param defValue
*            默认值
* @return
*/
public String getValues(String key, String defValue) {
String rtValue = null;

if (null == key) {
LOG.error("key is null");
} else {
rtValue = getPropertiesValue(key);
}

if (null == rtValue) {
LOG.warn("PropertyUtil.getValues return null, key is " + key);
rtValue = defValue;
}

LOG.info("PropertyUtil.getValues: key is " + key + "; Value is "
+ rtValue);

return rtValue;
}

/**
* 根据key值获取server.properties的值
*
* @param key
* @return
*/
private String getPropertiesValue(String key) {
String rtValue = demoProps.getProperty(key);

return rtValue;
}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息