java.util.Properties类是通过读取一个键值对文件来获得来一个值。我们通过把这个键值对文件称为配置文件。键值对文件的写法如下:
count=10
等于前后没有空格,从jdk1.5开始Properties类可以读取XML文件了。
下面通过一个类子来说明Properties类是怎么样增加程序的灵活性的
这个例子会用到的小程序
假设要求你写这个小程序的人要求你把NumSet的长度改为6,每运行一次这个小程序产生5组数据,你当然可以通过直接修改变量count的值,重新编译程序来实现。如果他又改变了想法,让你改变产生数据的范围,你需要再重复上面的操作,这看起来不是一个很好的选择^_^
通过引入Properties类,只需修改一下键对就的值就可以了,这样不是更轻松。具体做法:在RandomNum.java所在的目录建一下config目录,在config目录下建一文件randomNum.properties内容如下:
count=5
lengthCount=6
scope=12
对randomNum.properties文件的说明count:产生多少组数据lengthCount:每一组数据有多个整数组成scope:产生这些数据的范围。
在RandomNum.java所在的目录下新建一个PropertiesMgr.java类,用于读取randomNum.properties的值,内容如下:
importjava.io.IOException;
importjava.util.Properties;
publicclassPropertiesMgr {
staticPropertiesprops=newProperties();
static{
try{
props.load(PropertiesMgr.class.getClassLoader().getResourceAsStream("config/randomNum.properties"));
}catch(IOException e) {
e.printStackTrace();
}
}
//禁止new这个类的对象
privatePropertiesMgr() {}
publicstaticintgetProperty(String key) {
returnInteger.parseInt(props.getProperty(key));
}
调整的地方用红色标出
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
/**
*这个程序的主要目的是练习java数据结构set和list及泛型的使用
*功能:产生7组大于0小于33的整数,每一组有6个整数且不能有重复的数
* @author oak
*
*/
public class RandomNum {
public static void main(String[] args) {
int count = PropertiesMgr.getProperty("count");
ListnumSets = new ArrayList();//存放结果
//产生7组数据
for(int i=0; i
numSets.add(new NumSet());
}
//打印结果
for(int i=0; i
NumSet numSet = numSets.get(i);
System.out.println(numSet.toString());
}
}
}
/**
*这个类定义了符合要求的数据的结构
* @author oak
*
*/
class NumSet {
private int count = PropertiesMgr.getProperty("lengthCount");
Random r = new Random();
int scope;
Setnums = new HashSet();
public NumSet() {
scope = PropertiesMgr.getProperty("scope");
while(count > 0) {
// "+ 1":保证产生的数大于0
if(nums.add((r.nextInt(scope) + 1)))
{
//nums中每增加一个数,count--
count --;
}
}
}
public String toString() {
String str = "";
Iteratori = nums.iterator();
while(i.hasNext()) {
str += i.next()+ "\t";
}
return str;
}
}
目录结构如下:
D:\SourceCode\java\testProperties>dir
Volume in drive D has no label.
Volume Serial Number is D836-6EE7
Directory of D:\SourceCode\java\testProperties
2009-09-0616:52.
2009-09-0616:52..
2009-09-0616:51config
2009-09-0616:521,276 NumSet.class
2009-09-0616:52886 PropertiesMgr.class
2009-09-0616:44444 PropertiesMgr.java
2009-09-0616:52804 RandomNum.class
2009-09-0616:491,430 RandomNum.java
5 File(s)4,840 bytes