使用java程序读取配置文件中的相关属性值-asp.net关注

在开发企业应用的过程中,碰到很多权限问题,有时候有些权限的代码是要写在配置文件中的,这就需要我们在判断权限的时候,通过相应的程序读取出相关的属性值,程序代码如下.

代码示例:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* 获取系统property属性服务类
*
* @authorgavin
* 使用单例模式
*/
public class PropertyUtil {

private Log log = LogFactory.getLog(this.getClass());//记录日志


private static PropertyUtil instance = new PropertyUtil();

private static Properties properties;

private PropertyUtil() {

}

public static PropertyUtil getInstance() {
return instance;
}

public String getProperty(String key) {
if (properties == null || properties.size() == 0) {
properties = new Properties();
try {
properties.load(this.getClass().getResourceAsStream(
"/config.properties"));//配置文件所在的位置,一定要在根目录下面
} catch (FileNotFoundException e) {
log.error("未找到配置文件config.properties", e);
} catch (IOException e) {
log.error("读取配置文件config.properties出现异常", e);
} catch (Exception e) {
log.error("装载配置文件config.properties出现异常", e);
}
}
return properties.getProperty(key);
}
}

posted @ 2011-05-24 09:50  程承JAVA  阅读(297)  评论(0编辑  收藏  举报