浏览Apache的项目,突然发现Apache Configuration这个好东东,试用了一番,赞不绝口,于是就在这里推荐给各位朋友。http://jakarta.apache.org/commons/configuration/
我们写程序的时候经常需要对一些参数进行
动态配置,比如动态开辟内存的大小,要打开的文件名,可视化程序的背景颜色、窗体大小等等。通常我们会把这些变量写到一个配置文件中,程序每次启动的时候加载它并初始化各种参数,根据需要还可以把发生变化的参数写回配置文件。
<?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.langtech.org.cn/index.php/uid-5080-action-viewspace-itemid-70



















