您的位置:首页 > 运维架构 > Apache

Apache Configuration

2015-10-23 00:00 561 查看
浏览Apache的项目,突然发现ApacheConfiguration这个好东东,试用了一番,赞不绝口,于是就在这里推荐给各位朋友。http://jakarta.apache.org/commons/configuration/我们写程序的时候经常需要对一些参数进行动态配置,比如动态开辟内存的大小,要打开的文件名,可视化程序的背景颜色、窗体大小等等。通常我们会把这些变量写到一个配置文件中,程序每次启动的时候加载它并初始化各种参数,根据需要还可以把发生变化的参数写回配置文件。每到这个时候,读写配置文件是一个很繁琐的事情。需要先自己定义配置文件的格式,然后写代码打开文件,对关键字进行匹配,然后提取子串,再进行String到某类型的转换。总之这个过程是痛苦异常。现在有了ApacheConfiguration以后这个过程变得异常的轻松。下面我简单介绍一下ApacheConfiguration的用法。ApacheConfiguration可以处理多种格式的配置文件,这里我以最常用的XML配置文件为例。假设有一个配置文件名字为table.xml,其内容如下:<?xmlversion="1.0"encoding="ISO-8859-1"?> <gui-definition> <colors> <background>#808080</background> <text>#000000</text> <header>#008000</header> <linknormal="#000080"visited="#800080"/> <default>${colors.header}</default> </colors> <rowsPerPage>15</rowsPerPage> <buttons> <name>OK,Cancel,Help</name> </buttons> <numberFormatpattern="###\,###.##"/> </gui-definition>ApacheConfiguration读取这个配置文件的代码非常非常的简单。首先生成一个Configuration的实例,同时用xml文件名进行初始化。
try{
XMLConfigurationconfig=newXMLConfiguration("tables.xml");
}
catch(ConfigurationExceptioncex){
//somethingwentwrong,e.g.thefilewasnotfound
}
初始化完毕后,就可以进行参数的读取了
StringbackColor=config.getString("colors.background");StringtextColor=config.getString("colors.text");StringlinkNormal=config.getString("colors.link[@normal]");StringdefColor=config.getString("colors.default");introwsPerPage=config.getInt("rowsPerPage");Listbuttons=config.getList("buttons.name");
怎么样,是不是非常的简单:)除了读取参数之外还可以把修改过的参数存储到配置文件中。config.setProperty("background","#999999");
config.setProperty("rowsPerPage",82);
config.save();
简直是太方便了!以后用JAVA写程序再也不用怕繁琐的配置文件操作了!转载地址:http://www.cnblogs.com/ljkeke/archive/2009/02/02/1382265.html[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息