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

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

2013-08-27 21:03 826 查看
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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 实例
相关文章推荐