java 从属性文件加载数据的方法工具类 实例 可直接使用

来源:互联网 发布:网络鉴宝骗局 编辑:程序博客网 时间:2024/04/29 12:34

package com.alik.ecs.config;

import java.io.InputStream;
import java.util.Properties;

public class ConfigPropertiesUtil {

private static Properties prop = null;

//加载配置文件
static{ 
try {
loadProperties();
loadProperties2();
} catch (Exception e) {
e.printStackTrace();
}
  }
    //无参构造方法
public ConfigPropertiesUtil() {
}
    //加载配置文件方法
public static void loadProperties() throws Exception {
if (prop != null)
return;
prop = new Properties();
InputStream in = null;
try {
in = ConfigPropertiesUtil.class.getResourceAsStream("/source.properties");
prop.load(in);
} catch (Exception e) {
throw new Exception("[加载配置文件出错]", e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
throw new Exception("[关闭加载配置文件输入流出错]", e);
}
}
}
//加载配置文件方法
public static void loadProperties2() throws Exception {
if (prop != null)
return;
prop = new Properties();
InputStream in = null;
try {
in = ConfigPropertiesUtil.class.getResourceAsStream("/allusers.properties");
prop.load(in);
} catch (Exception e) {
throw new Exception("[加载配置文件出错]", e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
throw new Exception("[关闭加载配置文件输入流出错]", e);
}
}
}

    //根据key获取value值
public static String getProperty(String key) {
return prop.getProperty(key);
}

public static Properties getProperty() {
return prop;
}

public static String getProperty(String key, String defaultValue) {
String value = prop.getProperty(key);
if (value == null)
return defaultValue;


return value.trim();
}




public static void setProperty(String key, String value) {
prop.setProperty(key, value);
}


}
原创粉丝点击