`
xling09
  • 浏览: 12015 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

属性文件(properties)的使用

阅读更多
在系统研发过程中,对于一些需要经常使用的常量,属性文件可以进行灵活的配置,使用方法很多,我就自己在项目中的使用方式做一个总结:
1)首先要引入相应的jar包

2)然后可以创建一个辅助的类:
import java.util.Iterator;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

public class PropertiesUtil {
private static Configuration configuration;
private Configuration config;
public PropertiesUtil(String uri) throws ConfigurationException {
config = new PropertiesConfiguration(uri);
}

         //第一种使用方法
public String getValue(String key) {
return config.getString(key);
}

    public Iterator<String> getKeys(String value) {
       return config.getKeys(value);
    }
//第二种使用方法
public static String getPropertyValue(String uri, String key, String defaultValue) {
if(configuration == null) {
try {
configuration = new PropertiesConfiguration(uri);
} catch (ConfigurationException e) {
e.printStackTrace();
return defaultValue;
}
}
return configuration.getString(key, defaultValue);
}
}

3)在需要使用的地方(java类)创建静态代码块即可使用
private static String xxxX;

static{
try {
PropertiesUtil propertiesUtil=new PropertiesUtil("/xxxxxxx.properties");
xxx=propertiesUtil.getValue("xxxX");
} catch (ConfigurationException e) {
e.printStackTrace();
}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics