此程序依赖commons-configuration-1.6.jar和commons-lang-2.6.jar两个jar包。

需要先在工程的src目录下建立如下几个文件: 
config.properties代码:

  1. ip = 127.0.0.1
  2. port = 8081
  3. id = 111
  4. application.name = Killer App
  5. application.version = 1.6.2
  6. application.title = ${application.name} ${application.version}
  7. keys = cn,com,org,uk,edu,jp,hk
  8. enname =
  9. include = configiiff.properties

configiiff.properties代码:

  1. keysh = cn/com/org/uk/edu/jp/hk
  2. myname =shihuan

xmltest.xml代码:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <gui-definition>
  3. <colors>
  4. <background>#808080</background>
  5. <text>#000000</text>
  6. <header>#008000</header>
  7. <link normal="#000080" visited="#800080"/>
  8. <default>${colors.header}</default>
  9. </colors>
  10. <rowsPerPage>15</rowsPerPage>
  11. <buttons>
  12. <name>OK,Cancel,Help</name>
  13. <name>Yes,No,Cancel</name>
  14. </buttons>
  15. <numberFormat pattern="###\,###.##"/>
  16. </gui-definition>

database.xml代码:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <database>
  3. <tables>
  4. <table tableType="system">
  5. <name>users</name>
  6. <fields>
  7. <field>
  8. <name>uid</name>
  9. <type>long</type>
  10. </field>
  11. <field>
  12. <name>uname</name>
  13. <type>java.lang.String</type>
  14. </field>
  15. <field>
  16. <name>firstName</name>
  17. <type>java.lang.String</type>
  18. </field>
  19. <field>
  20. <name>lastName</name>
  21. <type>java.lang.String</type>
  22. </field>
  23. <field>
  24. <name>email</name>
  25. <type>java.lang.String</type>
  26. </field>
  27. </fields>
  28. </table>
  29. <table tableType="application">
  30. <name>documents</name>
  31. <fields>
  32. <field>
  33. <name>docid</name>
  34. <type>long</type>
  35. </field>
  36. <field>
  37. <name>name</name>
  38. <type>java.lang.String</type>
  39. </field>
  40. <field>
  41. <name>creationDate</name>
  42. <type>java.util.Date</type>
  43. </field>
  44. <field>
  45. <name>authorID</name>
  46. <type>long</type>
  47. </field>
  48. <field>
  49. <name>version</name>
  50. <type>int</type>
  51. </field>
  52. </fields>
  53. </table>
  54. </tables>
  55. </database>

config.ini代码:

  1. ; last modified 28 April 2011 by ShiHuan
  2. [owner]
  3. name=ShiHuan
  4. organization=Acme Products
  5. [database]
  6. server=192.168.2.67     ; use IP address in case network name resolution is not working
  7. port=1521

【注】:这里要简单介绍一下ini文件的格式,; 开头的是注释内容,每个[]是一个section,每个section下面有多个键值对。

TestConfiguration.java代码如下:

  1. import java.util.Collection;
  2. import java.util.Iterator;
  3. import java.util.List;
  4. import java.util.Set;
  5. import org.apache.commons.configuration.AbstractConfiguration;
  6. import org.apache.commons.configuration.AbstractFileConfiguration;
  7. import org.apache.commons.configuration.CompositeConfiguration;
  8. import org.apache.commons.configuration.Configuration;
  9. import org.apache.commons.configuration.ConfigurationException;
  10. import org.apache.commons.configuration.INIConfiguration;
  11. import org.apache.commons.configuration.PropertiesConfiguration;
  12. import org.apache.commons.configuration.XMLConfiguration;
  13. import org.apache.log4j.Logger;
  14. public class TestConfiguration {
  15. static Logger logger = Logger.getLogger(TestConfiguration.class);
  16. public static void readProperties(){
  17. //注意路径默认指向的是classpath的根目录
  18. Configuration config = null;
  19. try {
  20. config = new PropertiesConfiguration("config.properties");
  21. String ip = config.getString("ip");
  22. System.out.println(ip);
  23. int port = config.getInt("port");
  24. System.out.println(port);
  25. String title = config.getString("application.title");
  26. System.out.println(title);
  27. //再举个Configuration的比较实用的方法吧,在读取配置文件的时候有可能这个键值对应的值为空,那么在下面这个方法中
  28. //你就可以为它设置默认值。比如下面这个例子就会在test.properties这个文件中找id的值,如果找不到就会给id设置值为123
  29. //这样就保证了java的包装类不会返回空值。虽然功能很简单,但是很方便很实用。
  30. Integer id = config.getInteger("id", new Integer(123));
  31. System.out.println(id);
  32. //          config.setProperty("enname", "Hello");
  33. //          ((AbstractFileConfiguration) config).save();
  34. ((AbstractFileConfiguration) config).isAutoSave();
  35. config.setProperty("enname", "Hello");
  36. String emmname = config.getString("enname");
  37. System.out.println(emmname);
  38. //如果在properties 文件中有如下属性keys=cn,com,org,uk,edu,jp,hk
  39. //可以实用下面的方式读取:
  40. String[] keys1 = config.getStringArray("keys");
  41. for(int i=0; i<keys1.length; i++){
  42. System.out.println(keys1[i]);
  43. }
  44. System.out.println();
  45. System.out.println();
  46. List keys2 = config.getList("keys");
  47. for (Iterator iterator = keys2.iterator(); iterator.hasNext();) {
  48. String strKeys = (String) iterator.next();
  49. System.out.println(strKeys);
  50. }
  51. String myname = config.getString("myname");
  52. System.out.println(myname);
  53. } catch (ConfigurationException e) {
  54. logger.error(e.getMessage());
  55. }
  56. }
  57. public static void readPropertieshh(){
  58. try {
  59. AbstractConfiguration.setDefaultListDelimiter('/');  //设置指定分隔符
  60. Configuration config = new PropertiesConfiguration("configiiff.properties");
  61. String[] keys1 = config.getStringArray("keysh");
  62. for(int i=0; i<keys1.length; i++){
  63. System.out.println(keys1[i]);
  64. }
  65. System.out.println();
  66. System.out.println();
  67. List keys2 = config.getList("keysh");
  68. for (Iterator iterator = keys2.iterator(); iterator.hasNext();) {
  69. String strKeys = (String) iterator.next();
  70. System.out.println(strKeys);
  71. }
  72. } catch (ConfigurationException e) {
  73. logger.error(e.getMessage());
  74. }
  75. }
  76. public static void readXml(){
  77. try {
  78. XMLConfiguration config = new XMLConfiguration("xmltest.xml");
  79. /**
  80. *<colors>
  81. *  <background>#808080</background>
  82. *  <text>#000000</text>
  83. *  <header>#008000</header>
  84. *  <link normal="#000080" visited="#800080"/>
  85. *  <default>${colors.header}</default>
  86. *</colors>
  87. *这是从上面的xml中摘抄的一段,我们现在来解析它,
  88. *colors是根标签下的直接子标签,所以是顶级名字空间
  89. */
  90. String backColor = config.getString("colors.background");
  91. System.out.println(backColor);
  92. String textColor = config.getString("colors.text");
  93. System.out.println(textColor);
  94. //现在我们知道了如何读取标签下的数据,那么如何读标签中的属性呢?看下面
  95. //<link normal="#000080" visited="#800080"/>
  96. String linkNormal = config.getString("colors.link[@normal]");
  97. System.out.println(linkNormal);
  98. //还支持引用呢!
  99. //<default>${colors.header}</default>
  100. String defColor = config.getString("colors.default");
  101. System.out.println(defColor);
  102. //也支持其他类型,但是一定要确定类型正确,否则要报异常哦
  103. //<rowsPerPage>15</rowsPerPage>
  104. int rowsPerPage = config.getInt("rowsPerPage");
  105. System.out.println(rowsPerPage);
  106. //加属性
  107. config.addProperty("shihuan", "shihuan");
  108. config.addProperty("updatehala", "updatehala");
  109. System.out.println(config.getString("shihuan"));
  110. System.out.println(config.getString("updatehala"));
  111. //获得同名结点的集合
  112. List buttons = config.getList("buttons.name");
  113. for(Object button : buttons){
  114. System.out.println(button.toString());
  115. }
  116. System.out.println();
  117. System.out.println();
  118. //取消分隔符
  119. XMLConfiguration configList = new XMLConfiguration();
  120. configList.setDelimiterParsingDisabled(true);
  121. configList.setFileName("xmltest.xml");
  122. configList.load();
  123. List buttonsList = configList.getList("buttons.name");
  124. for(Object buttonList : buttonsList){
  125. System.out.println(buttonList.toString());
  126. }
  127. //更复杂的xml文件
  128. XMLConfiguration configXml = new XMLConfiguration();
  129. configXml.setDelimiterParsingDisabled(true);
  130. configXml.setFileName("database.xml");
  131. configXml.load();
  132. Object prop = configXml.getProperty("tables.table.name");
  133. if(prop instanceof Collection) {
  134. System.out.println("Number of tables: " + ((Collection) prop).size());
  135. }
  136. //return users
  137. System.out.println(configXml.getProperty("tables.table(0).name"));
  138. //return system
  139. System.out.println(configXml.getProperty("tables.table(0)[@tableType]"));
  140. //return documents
  141. System.out.println(configXml.getProperty("tables.table(1).name"));
  142. //return null,因为只有两个table所以这个值为null
  143. System.out.println(configXml.getProperty("tables.table(2).name"));
  144. //return [docid, name, creationDate, authorID, version]
  145. //如果所要找的节点不存在唯一值,则返回Collection类型
  146. System.out.println(configXml.getProperty("tables.table(1).fields.field.name"));
  147. //[long, long]
  148. //与上面的相同,返回值不唯一
  149. System.out.println(configXml.getProperty("tables.table.fields.field(0).type"));
  150. //return creationDate
  151. System.out.println(configXml.getProperty("tables.table(1).fields.field(2).name"));
  152. } catch (ConfigurationException e) {
  153. logger.error(e.getMessage());
  154. }
  155. }
  156. public static void readIni(){
  157. try {
  158. INIConfiguration config = new INIConfiguration("config.ini");
  159. String basestr = config.getBasePath();
  160. System.out.println(basestr);
  161. String filestr = config.getFileName();
  162. System.out.println(filestr);
  163. String pathstr = config.getPath();
  164. System.out.println(pathstr);
  165. Set zykhstr = config.getSections();
  166. for(Object setVal : zykhstr){
  167. System.out.println(setVal.toString());
  168. }
  169. System.out.println();
  170. System.out.println();
  171. for(Iterator iter = config.getKeys(); iter.hasNext();){
  172. System.out.println(iter.next().toString());
  173. System.out.println(config.getString(iter.next().toString()));
  174. }
  175. } catch (ConfigurationException e) {
  176. logger.error(e.getMessage());
  177. }
  178. }
  179. /**
  180. * @param args
  181. */
  182. public static void main(String[] args) {
  183. //      TestConfiguration.readProperties();
  184. //      TestConfiguration.readPropertieshh();
  185. //      TestConfiguration.readXml();
  186. TestConfiguration.readIni();
  187. }
  188. }
  189. //笔者在实际工作中封装好的类如下:
  190. import org.apache.commons.configuration.CompositeConfiguration;
  191. import org.apache.commons.configuration.ConfigurationException;
  192. import org.apache.commons.configuration.PropertiesConfiguration;
  193. /**
  194. * Created with IntelliJ IDEA.
  195. * User: yushibo
  196. * Date: 12-9-4
  197. * Time: 上午10:06
  198. * To change this template use File | Settings | File Templates.
  199. */
  200. public class PropertiesUtil {
  201. /**
  202. * 获取某个properties文件中的某个key对应的value值
  203. * @param fileName
  204. * @param key
  205. * @return 返回key说对应的value值
  206. * */
  207. public static String getPropertiesValue(String fileName, String key){
  208. CompositeConfiguration config = new CompositeConfiguration();
  209. PropertiesConfiguration pc = null;
  210. try {
  211. pc = new PropertiesConfiguration(fileName);
  212. config.addConfiguration(pc);
  213. String filevalue = config.getString(key).trim();
  214. return filevalue;
  215. } catch (ConfigurationException e) {
  216. e.printStackTrace();
  217. }
  218. return null;
  219. }
  220. /**
  221. * 获取某个properties文件中的某个key对应的value值(值是个数组)
  222. * @param fileName
  223. * @param key
  224. * @param delimiter
  225. * @return 返回key说对应的value数组值(使用时遍历数组值后要加.trim())
  226. * */
  227. public static String[] getPropertiesValues(String fileName, String key, char delimiter){
  228. CompositeConfiguration config = new CompositeConfiguration();
  229. PropertiesConfiguration pc = null;
  230. try {
  231. if(!Character.isWhitespace(delimiter)){
  232. AbstractConfiguration.setDefaultListDelimiter(delimiter);
  233. }
  234. pc = new PropertiesConfiguration(fileName);
  235. config.addConfiguration(pc);
  236. String[] filevalues = config.getStringArray(key);
  237. return filevalues;
  238. } catch (ConfigurationException e) {
  239. e.printStackTrace();
  240. }
  241. return null;
  242. }
  243. }
 

common-configuration的一些应用的更多相关文章

  1. [译]ASP.NET 5: New configuration files and containers

    原文:http://gunnarpeipman.com/2014/11/asp-net-5-new-configuration-files-and-containers/ ASP.NET vNext提 ...

  2. 黄聪:Microsoft Enterprise Library 5.0 系列教程(十) Configuration Application Block

    原文:黄聪:Microsoft Enterprise Library 5.0 系列教程(十) Configuration Application Block 到目前为止,我们使用的模块都是在同一个配置 ...

  3. 基于Common.Logging + Log4Net实现的日志管理

    前言 Common.Logging 是Commons-Logging(apache最早提供的日志门面接口,提供了简单的日志实现以及日志解耦功能) 项目的.net版本.其目的是为 "所有的.n ...

  4. 在C#应用中使用Common Logging日志接口

    我在C#应用中一般使用log4net来记录日志,但如果项目中有个多个工程,那么没有工程都需要引用log4neg,感觉很不爽.不过今日在开spring.net的时候,看到了有个通用日志接口Common ...

  5. ASP.NET Core 1.1.0 Release Notes

    ASP.NET Core 1.1.0 Release Notes We are pleased to announce the release of ASP.NET Core 1.1.0! Antif ...

  6. MyEclipse 的 配置文件

    D:\soft\i\myeclipse10\MyEclipse 10\configuration.settings\org.eclipse.ui.ide.prefs MAX_RECENT_WORKSP ...

  7. LinqToDB 源码分析——生成表达式树

    当我们知道了Linq查询要用到的数据库信息之后.接下就是生成对应的表达式树.在前面的章节里面笔者就已经介绍过.生成表达式树是事实离不开IQueryable<T>接口.而处理表达式树离不开I ...

  8. window 使用vagrant搭建开发开发环境

    # -*- mode: ruby -*-# vi: set ft=ruby : # All Vagrant configuration is done below. The "2" ...

  9. 【转】关于FLASH中图文混排聊天框的小结

    原文链接 图文混排也是FLASH里一个很古老的话题了,我们不像美国佬那样游戏里面聊天框就是聊天框,全是文字干干净净,也不像日本人发明了并且频繁地使用颜文字.不管是做论坛.做游戏,必定要实现的一点就是带 ...

  10. EF7 - What Does “Code First Only” Really Mean

    这篇文章很有价值,但翻译了一段,实在翻译不下去了,没办法,只能转载了. 英文地址:http://blogs.msdn.com/b/adonet/archive/2014/10/21/ef7-what- ...

随机推荐

  1. Vertex Lit 顶点光照

    http://blog.csdn.net/heyuchang666/article/details/51565102 顶点光照(Vertex Lit) 是最低保真度的光照.不支持实时阴影的渲染路径.最 ...

  2. OPENGL_单位长度对应屏幕像素

    gluPerspective(GLdouble fovy,GLdouble aspect,GLdouble zNear,GLdouble zFar) fovy:视角,指定视景体的视野的角度,以度数为单 ...

  3. [Xcode 实际操作]一、博主领进门-(4)设置项目的属性

    目录:[Swift]Xcode实际操作 本文将演示如何设置项目的属性. 点击项目名称[DemoApp],打开项目信息面板. [Identity识别]设置区域 [Display Name]:DemoAp ...

  4. Aandroid 解决apk打包过程中出现的“Certificate for <jcenter.bintray.com> doesn't match any of the subject alternative names: [*.aktana.com, aktana.com]”的问题

    有时候,apk打包过程中会出现“Certificate for <jcenter.bintray.com> doesn't match any of the subject alterna ...

  5. 大数据技术之_27_电商平台数据分析项目_02_预备知识 + Scala + Spark Core + Spark SQL + Spark Streaming + Java 对象池

    第0章 预备知识0.1 Scala0.1.1 Scala 操作符0.1.2 拉链操作0.2 Spark Core0.2.1 Spark RDD 持久化0.2.2 Spark 共享变量0.3 Spark ...

  6. Mybatis分页中遇到的坑3

    Mybatis Mapper.xml 配置文件中 resultMap 节点的源码解析   相关文章 Mybatis 解析配置文件的源码解析 Mybatis 类型转换源码分析 Mybatis 数据源和数 ...

  7. A - Bi-shoe and Phi-shoe

    每一个数字的欧拉函数要大于或等于该数字.求,最小的欧拉函数的下标和的大小. 答案要用longlong存 #include <iostream> #include <algorithm ...

  8. cmd,bat和dos的区别

    区别 dos是磁盘操作系统(Disk Operating System),是个人计算机上的一类操作系统. bat是DOS命令,在任何dos环境下都可以使用. bat文件是dos下的批处理文件,批处理文 ...

  9. shell学习(1)

    #!/bin/bash #######read从屏幕输入######## echo "what is your name?" read PERSON echo "Hell ...

  10. Zynq7000开发系列-4(新:Xilinx交叉编译环境搭建)

    一.前言  本来上一篇文章已经讲了Xilinx交叉编译环境的搭建,但是我在后续的使用中发现:使用2011年版本的交叉编译链编译OpenCV 3.1.0时出现错误: 网络搜索一番,查明是交叉编译链的问题 ...