文章源自:http://www.cnblogs.com/bakari/p/3562244.html
Properties类:
主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。
主要方法:
1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
示例及Enumeration接口使用:
Enumeration接口
文章说明:http://blog.csdn.net/zhiweianran/article/details/7672433
//随便配置一个配置文件(Test.properties)
name=JJ
Weight=4444
Height=3333
public class getProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
//实例化Properties类
Properties pps = new Properties();
//装载指定文件
pps.load(new FileInputStream("Test.properties"));
//Enumeration接口定义了从一个数据结构得到连续数据的手段。
Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
while(enum1.hasMoreElements()) {
String strKey = (String) enum1.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
}
}
}
//1.从dbconfig.properties当中读取链接配置
public class DbHelper {
private static String url;
private static String username;
private static String password;
private static String driver;
static{
Properties properties=new Properties();
//InputStream in=DbHelper.class.getResourceAsStream("/dbconfig.properties");
try {
//properties.load(in);
properties.load(new FileInputStream("/dbconfig.properties"));
url=properties.getProperty("url");
username=properties.getProperty("user");
password=properties.getProperty("password");
driver=properties.getProperty("driver");
} catch (IOException e) {
System.out.println("加载配置文件失败~");
}
}