public class SetConfig { public static void main(String[] args) { try { Configuration config = new Configuration(); //设置一些属性值 config.setValue("Max_Users_Count", "50"); config.setValue("Max_OpenedFile_Count", "20"); //保存文件 config.saveFile("system.conf", "Sytem Global Configuration"); } catch (ConfigurationException ex) { //捕获我们自定义的异常 ex.printStackTrace(); } } }
这段程序新建了一个配置,设置了两个配置项:Max_Users_Count为50;Max_OpenedFile_Count为20。最后将这个配置保存为system.conf文件,并加入抬头注释"Sytem Global Configuration"。执行之后,在程序所在目录下产生了一个system.conf文件,我们用纯文本编辑器打开看看内容到底是什么:
#Sytem Global Configuration #Mon Aug 02 23:43:39 PDT 2004 Max_OpenedFile_Count=20 Max_Users_Count=50
public class ReadConfig { public static void main(String[] args) { try { //读取指定文件 Configuration config = new Configuration("system.conf"); //获取特定值 System.out.println (config.getValue("Max_Users_Count") + " users can be actived at the same time"); //指定默认值 System.out.println (config.getValue("Max_OpenedFile_Count", "10") + " files can be opened at the same time"); } catch (ConfigurationException ex) { ex.printStackTrace(); } } }
系统输出了
50 users can be actived at the same time 20 files can be opened at the same time