apache commons-configuration包读取配置文件
1、pom依赖添加
<!-- 配置文件读取 -->
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.10</version>
</dependency>
2、读取.properties文件
使用PropertiesConfiguration配置类,主要示例代码如下:
public static final String fileName = "test.properties";
public static PropertiesConfiguration cfg = null; static {
try {
cfg = new PropertiesConfiguration(fileName);
} catch (ConfigurationException e) {
e.printStackTrace();
}
// 当文件的内容发生改变时,配置对象也会刷新
cfg.setReloadingStrategy(new FileChangedReloadingStrategy());
} /**
* 读String
* @param key
* @return
*/
public static String getStringValue(String key) {
return cfg.getString(key);
} /**
* 读int
* @param key
* @return
*/
public static int getIntValue(String key) {
return cfg.getInt(key);
} /**
* 读boolean
* @param key
* @return
*/
public static boolean getBooleanValue(String key) {
return cfg.getBoolean(key);
}
/**
* 读List
*/
public static List<?> getListValue(String key) {
return cfg.getList(key);
}
/**
* 读数组
*/
public static String[] getArrayValue(String key) {
return cfg.getStringArray(key);
}
test.properties可以如下定义:
name=king
port=21
flag=true
interest=guitar,piano
之后就可以用给定的一些读取方法操作了
String name = CGPropetiesUtil.getStringValue("name");
System.out.println("String:" + name);
3、读取.xml文件
使用XMLConfiguration配置类
主要代码
public static final String fileName = "test.xml";
public static XMLConfiguration cfg = null;
static {
try {
cfg = new XMLConfiguration(fileName);
} catch (Exception e) {
e.printStackTrace();
}
// 配置文件 发生变化就重新加载
cfg.setReloadingStrategy(new FileChangedReloadingStrategy());
}
public static String getStringValue(String key) {
return cfg.getString(key);
}
public static int getIntValue(String key) {
return cfg.getInt(key);
}
test.xml定义如下:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<database>
<url>127.0.0.1</url>
<port>1521</port>
<login>admin</login>
<password>admin</password>
</database>
</config>
测试操作同上。
4、对于一个文件来说,他的操作就对应一个配置类,而不能使用同一个配置类操作多个文件,否则它只以读取的第一个为操作对象。针对这种情况,可以写成一个通用的读取工具,简单示例如下:
public class CGCommonUtil {
/**
* 一个文件对应一个Configuration
*/
public static Map<String, Configuration> configMap = new ConcurrentHashMap<String, Configuration>();
/**
* 文件后缀
*/
private static final String SUFFIX_PROPERTIES = ".properties";
private static final String SUFFIX_XML = ".xml";
public static Configuration getConfig(String fileName) {
if (!configMap.containsKey(fileName)) {
CGCommonUtil.initConfig(fileName);
}
Configuration cfg = configMap.get(fileName);
if (null == cfg) {
throw new IllegalArgumentException("cfg is null");
}
return cfg;
}
private static void initConfig(String fileName) {
Configuration cfg = null;
try {
if (fileName.endsWith(SUFFIX_XML)) {
cfg = new XMLConfiguration(fileName);
} else if (fileName.endsWith(SUFFIX_PROPERTIES)) {
cfg = new PropertiesConfiguration(fileName);
}
} catch (ConfigurationException e) {
e.printStackTrace();
}
if (null != cfg) {
configMap.put(fileName, cfg);
} else {
System.out.println("cfg is null");
}
}
/**
* 读String
* @param key
* @return
*/
public static String getStringValue(Configuration cfg, String key) {
return cfg.getString(key);
}
/**
* 读int
* @param key
* @return
*/
public static int getIntValue(Configuration cfg, String key) {
return cfg.getInt(key);
}
/**
* 读boolean
* @param key
* @return
*/
public static boolean getBooleanValue(Configuration cfg, String key) {
return cfg.getBoolean(key);
}
/**
* 读List
*/
public static List<?> getListValue(Configuration cfg, String key) {
return cfg.getList(key);
}
/**
* 读数组
*/
public static String[] getArrayValue(Configuration cfg, String key) {
return cfg.getStringArray(key);
}
public static void main(String[] args) {
Configuration config = getConfig("test.properties");
String name1 = getStringValue(config, "name");
}
}
以上可以作为一个通用的读取工具,为每一个文件都设置了一个相应的配置操作类,如果考虑本地缓存影响会影响内存的话可以考虑定时删除缓存数据操作
5、Configuration读取文件源原
入口类ConfigurationUtils

主要涉及的方法如下:
locateFromClasspath方法:
static URL locateFromClasspath(String resourceName) {
URL url = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader != null) {
url = loader.getResource(resourceName);
if (url != null) {
LOG.debug("Loading configuration from the context classpath (" + resourceName + ")");
}
}
if (url == null) {
url = ClassLoader.getSystemResource(resourceName);
if (url != null) {
LOG.debug("Loading configuration from the system classpath (" + resourceName + ")");
}
}
return url;
}
首先它通过获取了当前线程的一个类加载器,通过加载器的getResouce方法去类加载器找到resourceName这个文件
getResouce方法:
public URL getResource(String name) {
URL url;
if (parent != null) {
url = parent.getResource(name);
} else {
url = getBootstrapResource(name);
}
if (url == null) {
url = findResource(name);
}
return url;
}
先去父节点的loader去加载资源文件,如果找不到,则会去BootstrapLoader中去找,如果还是找不到,才调用当前类的classLoader去找。这也就是JDK类加载的双亲委派模型。
getInputStream方法:
public InputStream getInputStream(URL url) throws ConfigurationException {
File file = ConfigurationUtils.fileFromURL(url);
if (file != null && file.isDirectory()) {
throw new ConfigurationException("Cannot load a configuration from a directory");
} else {
try {
return url.openStream();
} catch (Exception var4) {
throw new ConfigurationException("Unable to load the configuration from the URL " + url, var4);
}
}
}
调用url的openStream()方法去获得此文件的输入流
GItHub源码参照
apache commons-configuration包读取配置文件的更多相关文章
- Apache Commons Configuration的应用
Apache Commons Configuration的应用 Commons Configuration是一个java应用程序的配置管理工具.可以从properties或者xml文件中加载软件的配置 ...
- Apache Commons Configuration读取xml配置
近期项目自己手写一个字符串连接池.因为环境不同有开发版本.测试版本.上线版本.每一个版本用到的数据库也是不一样的.所以需要能灵活的切换数据库连接.当然这个用maven就解决了.Apache Commo ...
- 使用Apache Commons Configuration读取配置信息
在项目中使用一些比较新的库总会给你带来很多快乐,在这篇文章中,我将会给你介绍一个在Java中读取配置文件的框架——Apache Commons Configuration framework. 你会了 ...
- apache commons io包基本功能
1. http://jackyrong.iteye.com/blog/2153812 2. http://www.javacodegeeks.com/2014/10/apache-commons-io ...
- apache commons lang包中的StringUtils
计算一个字符串某个字符的出现次数 a, 使用charAt方法截取之后,循环判断. b, 使用apache commons lang包中的StringUtils: int n = StringUtils ...
- apache commons Java包简介
更多信息,请参考:http://commons.apache.org/ 一.Commons BeanUtils说明:针对Bean的一个工具集.由于Bean往往是有一堆get和set组成,所以BeanU ...
- Apache Commons configuration使用入门
使用Commons Configuration可以很好的管理我们的配置文件的读写, 官网:http://commons.apache.org/configuration 需要用到commons-la ...
- IO与文件读写---使用Apache commons IO包提高读写效率
觉得很不错,就转载了, 作者: Paul Lin 首先贴一段Apache commons IO官网上的介绍,来对这个著名的开源包有一个基本的了解:Commons IO is a library of ...
- jar包读取配置文件
读取jar包内配置文件: Properties config = new Properties(); InputStream in = this.getClass().getClassLoader() ...
- 使用Apache Commons IO组件读取大文件
Apache Commons IO读取文件代码如下: Files.readLines(new File(path), Charsets.UTF_8); FileUtils.readLines(new ...
随机推荐
- [转帖]70亿!以色列间谍产品公司NSO要被卖掉了
70亿!以色列间谍产品公司NSO要被卖掉了 2017-06-14 11:11 https://www.sohu.com/a/148739327_257305 E安全6月14日讯以色列的网络能力处于世界 ...
- AtCoder-arc058(题解)
A - こだわり者いろはちゃん / Iroha's Obsession(暴力) 题目链接 题目大意: 给你 \(k\) 个个位数字和一个数字 \(n\) ,要求找到一个大于等于n的数字,使得不出现 \ ...
- PHP 去一定范围随机小数 随机浮点数
例如取2到3中的 随机小数(一位)或整数 mt_rand(20,30)/10 mt_rand()是随机取整函数 先扩大一定倍数,再缩小相应倍数,倍数代表精确到哪一位
- Python有用的内置函数divmod,id,sorted,enumerate,input,oct,eval,exec,isinstance,ord,chr,filter,vars,zip
divmod(a, b) 函数接收两个数字类型(非复数)参数,返回一个包含商和余数的元组(a // b, a % b) id() 函数用于获取对象的内存地址. sorted(iterable, key ...
- 解决clover配置文件conf.plist中nv_disable=1或者nvda_drv=1不生效或者说不能删除的问题
情况一:U盘安装MacOS的时候conf.plist中设置了nv_disable=1,但是启动的时候任然显示nvda_drv=1. 这种情况一般出现在该机器曾经安装过MacOS,MacOS会将这个参数 ...
- java注解注意点
注意:以后工作中代码中 不允许出现警告 自定义注解 1:自定义注解并没有发挥它的作用,而Eclipse自带的注解通过反射另外有一套代码,可以发挥它的作用,例如:跟踪代码...... 2:如果自定义的代 ...
- Ambari深入学习(III)-开源使用及其改进思考
Ambari采用的不是一个新的思想和架构,也不是完成了软件的新的革命,而是充分利用了一些已有的优秀开源软件,巧妙地把它们结合起来,使其在分布式环境中做到了集群式服务管理能力.监控能力.展示能力.这些优 ...
- navicat连接mysql出现2059
1.找到mysql的目录:C:\Program Files\MySQL\MySQL Server 8.0\bin 2.清空此目录,输入cmd,回车 3.在控制台输入:mysql -u root -p ...
- c# sharepoint client object model 客户端如何创建中英文站点
c# sharepoint client object model 客户端如何创建中英文站点 ClientContext ClientValidate = tools.GetContext(Onlin ...
- docker swarm yaml
https://www.cnblogs.com/bigberg/p/8867326.html 一.简介 Docker有个编排工具docker-compose,可以将组成某个应该的多个docker容器编 ...