Properties类与读取properties文件

Properties类

在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。

这个类的几个常用的方法:

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

举个例子,比如要搜索"PORT"对应的值,getProperty ("PORT") 返回的值就是properties文件中PORT对应的值。

2.load(InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。

例如:类名.class.getClassLoader().getResourceAsStream(配置文件) 这个语句的返回值是一个InputStream,然后 进行装载就好了。

3. setProperty ( String key, String value),用来设置设置 键 - 值对

Properties extends Hashtable

public synchronized Object setProperty(String key, String value) {
        return put(key, value);
    }

使用基类的put方法

操作的是内存里的数据 ,而本地的文件是不动的

4. store ( OutputStream out, String comments) 这个是将此 Properties 表中的属性列表(键和元素对)写入输出流,将键 - 值对写入到指定的文件中去。

5.clear (),清除所有装载的 键 - 值对。基类的方法。

*********************************************************************************

这是个小例子

*********************************************************************************

public class Tools {
 private static Properties p=new Properties();
 /**
  * 读取sys.properties配置文件信息
  */
 static{
  try {
   //通过Properties对象的load方法加载资源文件
   p.load(Tools.class.getClassLoader().getResourceAsStream("a.properties"));
   System.out.println(p);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 /**
  * 根据key得到value的值
  * getProperty(String key)用指定的键在此属性列表中搜索属性。
  */
 public static String getValue(String key){
  return p.getProperty(key);
 }
}

 *********************************************************************************

原文地址:https://www.cnblogs.com/liangxiaoyu/p/4833754.html