使用apache commons包读取配置文件
在java项目中, 经常需要从配置文件中读取配置信息. 常见的配置文件有properties文件和XML文件.本文以读取properties配置文件为例.
配置文件 app.properties 截取如下:

2

3

4

加载并读取配置

2

3

4

5


6

7

8

9

10

11

12

13

14
private static String CONFIG_FILEPATH = ClassLoader.getSystemResource(
“app.properties”).getPath();

15
16
17private static void initFromProperties()
18{
19 try
20 {
21 CONFIG_FILEPATH = URLDecoder.decode(CONFIG_FILEPATH, “utf-8”);
22 setProperties(new PropertiesConfiguration(CONFIG_FILEPATH));
23 getProperties().setReloadingStrategy(
24 new FileChangedReloadingStrategy());
25 getProperties().setAutoSave(true);
26
27 readValues();
28 }
29 catch (UnsupportedEncodingException e)
30 {
31 //处理异常
32 }
33 catch (ConfigurationException e)
34 {
35 //处理异常
}
36
37 }
38
39
40
41 private static void readValues()
42 {
43 // ftp
44 setFtpUser(getStrValue(“ftp.username”));
45 setFtpPassword(getStrValue(“ftp.password”));
46 setFtpHost(getStrValue(“ftp.hostip”));
47 setFtpRootPath(getStrValue(“ftp.ftproot”));
48 setFtpPort(getStrValue(“ftp.port”));
49 }
50
51
52
53
同样对于XML配置文件,也可以使用apache commons包.