1 import java.io.BufferedReader;
2 import java.io.IOException;
3 import java.io.InputStream;
4 import java.io.InputStreamReader;
5 import java.util.Properties;
6
7 import org.apache.commons.logging.Log;
8 import org.apache.commons.logging.LogFactory;
9
10 /**
11 * 配置文件读取工具
12 */
13 public class ConfigurableConstants
14 {
15
16 protected static final String PROPERTIES_PATH = "config.properties";
17
18 protected static Log logger = LogFactory.getLog(ConfigurableConstants.class);
19 protected static Properties p = new Properties();
20 static
21 {
22 init(PROPERTIES_PATH);
23 }
24
25 /**
26 * 静态读入属性文件到Properties p变量中
27 */
28 protected static void init(String propertyFileName)
29 {
30 InputStream in = null;
31 try
32 {
33 // class.getClassLoader()获得该class文件加载的web应用的目录,如WEB-INF/classes/就是根目录
34 // getResourceAsStream(relativeFilePath):定位该文件且获得它的输出流
35 in = ConfigurableConstants.class.getClassLoader().getResourceAsStream(propertyFileName);
36 BufferedReader bf = null;
37 if (in != null)
38 // load输出流到Properties对象中
39 // 因为字节流是无法读取中文的,所以采取reader把inputStream转换成reader用字符流来读取中文。
40 bf = new BufferedReader(new InputStreamReader(in));
41 p.load(bf);
42 }
43 catch (IOException e)
44 {
45 logger.error("load " + propertyFileName + " into Constants error!");
46 }
47 finally
48 {
49 if (in != null)
50 {
51 try
52 {
53 in.close();
54 }
55 catch (IOException e)
56 {
57 logger.error("close " + propertyFileName + " error!");
58 }
59 }
60 }
61 }
62
63 /**
64 * 封装了Properties类的getProperty函数,使p变量对子类透明.
65 *
66 * @param key
67 * property key.
68 * @param defaultValue
69 * 当使用property key在properties中取不到值时的默认值.
70 */
71 public static String getProperty(String key, String defaultValue)
72 {
73 return p.getProperty(key, defaultValue).trim();
74 }
75
76 }