1
import java.io.FileInputStream;
2
import java.io.FileOutputStream;
3
import java.util.HashMap;
4
import java.util.Iterator;
5
import java.util.Properties;
6
7
8
/**
9
* 功能:解析資源文件
10
*
11
*/
12
public class PropertyUtil {
13
14
private Properties property=new Properties();
15
private String filepath="";
16
17
/**
18
* 解析資源文件的類的構造函數
19
* @param path 文件索在的包,如:com.cn.myproperty.dbo.properties
20
*/
21
public PropertyUtil(String path){
22
try {
23
filepath=this.getClass().getResource("/").getPath();
24
filepath=filepath+path;
25
26
27
property.load(new FileInputStream(filepath));
28
} catch (Exception e) {
29
e.printStackTrace();
30
}
31
}
32
33
34
/**
35
* 返回資源文件的hashmap對象
36
*/
37
public HashMap getElements(){
38
HashMap map=new HashMap ();
39
Iterator it=this.property.keySet().iterator();
40
while(it.hasNext()){
41
String key = it.next().toString();
42
map.put(key, property.getProperty(key));
43
}
44
return map;
45
}
46
47
48
//返回資源文件里的值
49
public String getvalue(String key){
50
if(key!=null)
51
return this.property.getProperty(key);
52
else
53
return "";
54
}
55
56
//設置資源文件里的值
57
public boolean setvalue(String key,String value){
58
if(key!=null)
59
{
60
try{
61
this.property.setProperty(key,value);
62
this.property.store(new FileOutputStream(filepath), filepath);
63
return true;
64
}catch(Exception ex){
65
System.out.println("保存資源文件出錯了"+this);
66
}
67
}
68
return false;
69
}
70
71
72
}
73

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

1
import java.util.HashMap;
2
3
4
public class ConfigManager {
5
private static HashMap map=null;
6
static{
7
if(map==null){
8
PropertyUtil propertyUtil = new PropertyUtil("property.properties");
9
map=propertyUtil.getElements();
10
}
11
}
12
/**
13
* 得到SystemConfig資源文件中定義的值,如果未定義則返回空字符串,不是null
14
* @param key
15
* @return
16
*/
17
public static String getValue(String key){
18
try{
19
return map.get(key).toString();
20
}catch(Exception ex){
21
System.out.println(ConfigManager.class+">>> zi yuan wen jian mei you ding yi key suo dui ying de zhi");
22
return "";
23
}
24
}
25
26
}
頁面使用:
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

1
ConfigManager.getValue(******)
