Properties类 与 System类

Properties :派生自Hashtable。主要是用来存储字符串类型的键值对。Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

 

System类可以返回一个系统的属性。通过getProperties()方法可以检测当前系统的属性,然后返回Properties类型的一个对象,当它返回这个对象之后,可以用一个List(PrintStream out)打印系统属性。System.out中的这个out的类型就是PrintStream。

 

代码
import java.util.Properties;

public class PropertiesTest {
public static void main(String[] args) {

// Properties java.lang.System.getProperties()
// Determines(确定) the current system properties
Properties pps = System.getProperties();

// void java.util.Properties.list(PrintStream out)
// 将属性列表输出到指定的输出流。
pps.list(System.out);

// 获取当前操作系统名
System.out.println("当前操作系统名:" + System.getProperty("os.name"));

// 这个特别有用,在IO那节。
System.out.println("当前应用程序所在位置:" + System.getProperty("user.dir")); }
}

 

 

 

利用Properties类来读取一个配置文件。

代码
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

public class PropTest {
public static void main(String[] args) {
Properties pps
= new Properties();
try {
pps.load(
new FileInputStream("aaa.ini"));
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}

// Enumeration<?> java.util.Properties.propertyNames()
// 返回属性列表中所有键的枚举,如果在主属性列表中未找到同名的键,则包括默认属性列表中不同的键。
Enumeration<?> enumeration = pps.propertyNames();

// Enumeration<?> java.util.Properties.propertyNames()
// 判断是否有更多的元素
while (enumeration.hasMoreElements()) {
// ? java.util.Enumeration.nextElement()
// 取出键
String strKey = (String) enumeration.nextElement();

// String java.util.Properties.getProperty(String key)
// 指定键所对应的值。
String strValues = pps.getProperty(strKey);

// 打印aaa.ini的键和值
System.out.println(strKey + "=" + strValues);
}

}
}

 

那么以后在编写自己的程序的时候,就可以利用这个类的特点,将我们在运行时候需要读取的一些配置信息写到一个文件当中,然后当这个程序启动的时候,再从这个文件当中读取我们想要的信息。

posted @ 2010-12-23 12:38  meng72ndsc  阅读(255)  评论(0编辑  收藏  举报