[实训]Java中的Properties类

来源:互联网 发布:php java 编辑:程序博客网 时间:2024/06/06 00:57

这是Java自带的一个解析.properties配置文件的类。

Properties
它提供了几个主要的方法:

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 (),清除所有装载的 键 - 值对。该方法在基类中提供。

在平时的web项目开发中用的比较普遍。在c3p0插件加载的时候,可以这么用:

        Properties p = PropertyKit.load("db.properties");        C3p0Plugin cp = new C3p0Plugin(p.getProperty("driver"), p.getProperty("user"), p.getProperty("password"));

这样就能在不用修改源文件代码的情况下,动态的修改数据库配置信息,相当好用。

常规用法如下:

import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream; import java.util.Iterator;import java.util.Properties; public class PropertiesTest {    public static void main(String[] args) {         Properties prop = new Properties();             try{            //读取属性文件test.properties            InputStream in = new BufferedInputStream (new FileInputStream("test.properties"));            prop.load(in);     //加载属性列表            Iterator<String> it=prop.stringPropertyNames().iterator();            while(it.hasNext()){                String key=it.next();               System.out.println(key+":"+prop.getProperty(key));            }            in.close();            ///保存属性到a.properties文件            FileOutputStream oFile = new FileOutputStream("a.properties", true);//true表示追加打开            prop.setProperty("test1", "111111");            prop.store(oFile, "The New properties file");            oFile.close();        }        catch(Exception e){            System.out.println(e);        }    } }

以上。