浏览Apache的项目,突然发现
Apache Configuration
这个好东东,试用了一番,赞不绝口,于是就在这里推荐给各位朋友。
http://jakarta.apache.org/commons/configuration/
我们写程序的时候经常需要对一些参数进行
动态配置,比如动态开辟内存的大小,要打开的文件名,可视化程序的背景颜色、窗体大小等等。通常我们会把这些变量写到一个配置文件中,程序每次启动的时候加载它并初始化各种参数,根据需要还可以把发生变化的参数写回配置文件。
每到这个时候,读写配置文件是一个很繁琐的事情。需要先自己
定义配置文件的格式,然后写代码打开文件,对关键字进行匹配,然后提取子串,再进行String到某类型的转换。总之这个过程是痛苦异常。
现在有了
Apache Configuration 以后这个过程变得异常的轻松。下面我简单介绍一下
Apache Configuration 的用法。
Apache Configuration 可以处理多种格式的配置文件,这里我以最常用的XML配置文件为例。假设有一个配置文件名字为table.xml,其内容如下:
<?xml version="1.0" encoding="ISO-8859-1" ?> <gui-definition> <colors> <background>#808080</background> <text>#000000</text> <header>#008000</header> <link normal="#000080" visited="#800080"/> <default>${colors.header}</default> </colors> <rowsPerPage>15</rowsPerPage> <buttons> <name>OK,Cancel,Help</name> </buttons> <numberFormat pattern="###\,###.##"/> </gui-definition>用Apache Configuration 读取这个配置文件的代码非常非常的简单。首先生成一个Configuration的实例,同时用xml文件名进行初始化。
try { XMLConfiguration config = new XMLConfiguration("tables.xml"); } catch(ConfigurationException cex) { // something went wrong, e.g. the file was not found } 初始化完毕后,就可以进行参数的读取了String backColor = config.getString("colors.background"); String textColor = config.getString("colors.text"); String linkNormal = config.getString("colors.link[@normal]"); String defColor = config.getString("colors.default"); int rowsPerPage = config.getInt("rowsPerPage"); List buttons = 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