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

java读取properties文件配置

2012-06-18 18:59 656 查看
package test;

import java.io.InputStream;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Properties;

import java.util.Set;

public class SysConfigUtils {

public SysConfigUtils() {

}

private static SysConfigUtils me = null;

private Map<String, String> cfg = new HashMap<String, String>();

public static SysConfigUtils getInstance() {

if (me == null) {

me = new SysConfigUtils();

me.readConfig();

}

return me;

}

//读取配置文件properties

private void readConfig() {

Properties properties = new Properties();

InputStream file = this.getClass().getResourceAsStream(

"/datasource.properties");

try{

properties.load(file);

}catch(Exception e){

return;

}

Set keys = properties.keySet();

Iterator it = keys.iterator();

while(it.hasNext()){

String key = (String) it.next();

String value = properties.getProperty(key);

this.cfg.put(key, value);

}

}

public String getConfig(String key){

if(cfg==null){

readConfig();

}

if(!this.cfg.containsKey(key)){

return null;

}

return (String) this.cfg.get(key);

}

//测试

public static void main(String[] args) {

System.out.println(SysConfigUtils.getInstance().getConfig("username"));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息