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"));
}
}
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"));
}
}
相关文章推荐
- Java读取Properties配置文件几点注意事项
- java 读取Properties类型的配置文件参数值
- Java配置properties文件的加载和读取方法
- java 读取properties配置文件
- java中读取.properties配置文件
- Java读取properties配置文件
- java读取properties配置文件
- java中读取properties配置文件用例
- Java读取properties配置文件时,中文乱码解决方法
- Java Web项目如何读取.properties配置文件
- java读取properties配置文件
- JAVA读取classess下的.properties配置文件封装类
- Java 读取properties配置文件
- Hibernate从Java属性文件(properties)读取配置信息
- java对配置文件.properties文件读取的几种方法
- java读取配置Properties文件
- Java Properties 类读取配置文件信息
- Java读取properties配置文件时,中文乱码解决方法
- 【Properties文件】Java使用Properties来读取配置文件
- java修改读取properties配置文件中的内容