common-configuration的一些应用

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

需要先在工程的src目录下建立如下几个文件: 
config.properties代码: 
Java代码  收藏代码
  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代码: 
Java代码  收藏代码
  1. keysh = cn/com/org/uk/edu/jp/hk  
  2. myname =shihuan  


xmltest.xml代码: 
Java代码  收藏代码
  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代码: 
Java代码  收藏代码
  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代码: 
Java代码  收藏代码
  1. ; last modified 28 April 2011 by ShiHuan  
  2. [owner]  
  3. name=ShiHuan  
  4. organization=Acme Products  
  5.    
  6. [database]  
  7. server=192.168.2.67     ; use IP address in case network name resolution is not working  
  8. port=1521  

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

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