java 获取配置文件中的属性值
java web 应用,很多场景需要用到配置文件中的各个属性值。java Properties 类可以实现这类功能。源码如下所示。
package *****.utils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
/**
* @description
* @date 2018/7/11 17:22
*/
public class PropertyUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
/**
* 从指定配置文件获取指定属性值
* @param path 文件路径,如:D://testConfig.properties
* @param key 属性,如:testLock
* @return testLock 的属性值
*/
public static String getProperties(String path, String key) {
Properties prop = new Properties();
InputStream in = null;
String value = null;
try {
// 通过输入缓冲流进行读取配置文件
in = new BufferedInputStream(new FileInputStream(new File(path)));
// 加载输入流
prop.load(in);
// 根据关键字获取value值
value = prop.getProperty(key);
} catch (Exception e) {
logger.error(ExceptionUtils.getFullStackTrace(e));
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
logger.error(ExceptionUtils.getFullStackTrace(e1));
}
}
}
return value;
}
}
还没有评论,来说两句吧...