适用于 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;
- }
- }
来源: http://www.bubuko.com/infodetail-2712781.html