`

Properties类

阅读更多
首先看一下继承关系,HashTable是继承自Dictionary,而Properties又是继承自HashTabel。
即关系如下
java.lang.Object
  java.util.Dictionary<K,V>
      java.util.Hashtable<Object,Object>
Properties要求的key和value都是String类型的。
Properties的setProperty方法是线程安全的。
其常用方法
构造方法
1.Properties()
2.getProperty(String key)//获取指定key的value
3.getProperty(String key, String defaultValue)//返回key,如果没有找到返回默认值
4.load(InputStream inStream)//从字节流读取键值对到properties
5.load(Reader reader)//从字符流读取键值对
实例:从properties文件读取数据
Properties pro = new Properties();
InputSteam is = new BufferedInputStream(FileInputStream(filePath));
pro.load(is);
String value = pro.getProperty(key);
6.propertyNames()返回的是一个Enumeration
实例遍历properties
Properties pro = new Properties();
InputSteam is = new BufferedInputStream(FileInputStream(filePath));
pro.load(is);
Enumeration enum= pro.propertyNames();
for(;enum.hasMoreElements();){
   String key = (String)enum.nextElement();//返回的是泛型指定类型
   String value = pro.getProperty(key);
}
7.loadFromXML(InputStream in)//获取指向xml的所有属性
8.setProperty(String key, String value)//添加键值对到pro对象中
9.store(OutputStream out, String comments)//将键值对写入输出流所对应的文件中,comments表示对应的注释
实例
Properties pro = new Properties();
InputSteam is = new BufferedInputStream(FileInputStream(filePath));
pro.load(is);
//设置属性
pro.setProperty("写入的key","写入的value");
//然后调用store写入文件中 
FileOutputSream os = new FileOutputSream(filePath);
pro.store(os,"添加练习");
10.loadFromXML(InputStream in)//加载xml文件的属性
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics