1.package com.billows.util;
2.
3.import java.io.*;
4.import java.util.*;
5.
6./**
7. * java 读取配置(属性)文件
8. * @author Billows.Van
9. * billows.van@gmail.com
10. */
11.public class EnvironmentConfig {
12. static EnvironmentConfig ec;// 创建对象ec
13. private static Hashtable<String, Properties> register = new Hashtable<String, Properties>();// 静态对象初始化[在其它对象之前]
14.
15. private EnvironmentConfig() {
16. super();
17. }
18.
19. /**
20. * 取得EnvironmentConfig的一个实例
21. */
22. public static EnvironmentConfig getInstance() {
23. if (ec == null)
24. ec = new EnvironmentConfig();// 创建EnvironmentConfig对象
25. return ec;// 返回EnvironmentConfig对象
26. }
27.
28. /**
29. * 读取配置文件
30. */
31. public Properties getProperties(String fileName) {// 传递配置文件路径
32. InputStream is = null;// 定义输入流is
33. Properties p = null;
34. try {
35. p = (Properties) register.get(fileName);// 将fileName存于一个HashTable
36. /**
37. * 如果为空就尝试输入进文件
38. */
39. if (p == null) {
40. try {
41. is = new FileInputStream(fileName);// 创建输入流
42. } catch (Exception e) {
43. if (fileName.startsWith("/"))
44. // 用getResourceAsStream()方法用于定位并打开外部文件。
45. is = EnvironmentConfig.class.getResourceAsStream(fileName);
46. else
47. is = EnvironmentConfig.class.getResourceAsStream("/"+fileName);
48. }
49. p = new Properties();
50. p.load(is);// 加载输入流
51. register.put(fileName, p);// 将其存放于HashTable缓存
52. is.close();// 关闭输入流
53. }
54. } catch (Exception e) {
55. e.printStackTrace(System.out);
56. }
57. return p;// 返回Properties对象
58. }
59.
60. /**
61. * 此处插入方法描述。
62. */
63. public String getPropertyValue(String fileName, String strKey) {
64. Properties p = getProperties(fileName);
65. try {
66. return (String) p.getProperty(strKey);
67. } catch (Exception e) {
68. e.printStackTrace(System.out);
69. }
70. return null;
71. }
72.}
用法:
1.EnvironmentConfig ec=EnvironmentConfig.getInstance();
2.String driverClassName=ec.getPropertyValue("/config/jdbc.properties", "jdbc.driverClassName");