Properties类

简介:

Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各类语言都有本身所支持的配置文件,配置文件中不少变量是常常改变的,这样作也是为了方便用户,让用户可以脱离程序自己去修改相关的变量设置。code

主要的方法:

1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是经过参数 key ,获得 key 所对应的 value。资源

2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。经过对指定的文件(好比说上面的 test.properties 文件)进行装载来获取该文件中的全部键 - 值对。以供 getProperty ( String key) 来搜索。get

3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他经过调用基类的put方法来设置 键 - 值对。io

4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。table

5. clear (),清除全部装载的 键 - 值对。该方法在基类中提供。class

读取文件的方法:

InputStream in = getClass().getResourceAsStream("资源Name");test

或者变量

InputStream in = new BufferedInputStream(new FileInputStream(filepath));配置

例子:

配置文件file

文件名:Test.properties

name=wangwei
phone=18334702840

读取

public class getProperties {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        Properties pps = new Properties();
        //pps.load(new FileInputStream("Test.properties"));
        getProperties gP = new getProperties();
        String FileName = "Test.properties";
        InputStream is=gP.getClass().getResourceAsStream(FileName);
        pps.load(is);
        Enumeration enum1 = pps.propertyNames();//获得配置文件的名字
        while(enum1.hasMoreElements()) {
            String strKey = (String) enum1.nextElement();
            String strValue = pps.getProperty(strKey);
            System.out.println(strKey + "=" + strValue);
        }
    }
}
相关文章
相关标签/搜索