目录
Properties集合介绍
- 是一个Map体系的集合类
- Properties类表示一种持久属性,可以保存在流或者从流中加载
- 属性列表中的每个键值对及其对应的值都是一个字符串
- Properties 继承于 Hashtable,在使用方法getProperty()与get()中,getProperty()只能取字符串的数值,而get方法可以获取任意属性,所以Properties可以用put和get方法,但是不建议setProperty()、getProperty()和put()、get()方法互相混用,否则会出现取不出的情况
Properties集合的遍历
1、KeySet方法
返回此地图中包含的键的Set
视图,即将键作为元素返回在Set集合中,通过get(key)方法返回键的值。返回一个Set集合,并且这个Set可以对映射支持,就是在map集合的改动,在这个set集合中也可以反映出来
public class demo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("1", "11");
properties.put("2", "22");
properties.put("3", "31");
properties.put("4", "41");
Set<Object> keySet = properties.keySet();
for (Object key : keySet) {
System.out.println(key + ": " + properties.get(key));
}
}
}
2、EntrySet方法
使用EntrySet()方法包装了键值对,返回一个此Map中包含的映射的Set视图,通过get()方法在访问键值对。
public class demo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("1", "11");
properties.put("2", "22");
properties.put("3", "31");
properties.put("4", "41");
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
for (Map.Entry<Object, Object> map : entries) {
System.out.println(map.getKey() + ":" + map.getValue());
}
}
}
3、propertyNames()方式
返回此属性列表中所有键的枚举,包括默认属性列表中的不同键,如果尚未从主属性列表中找到相同名称的键。
public class demo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("1", "11");
properties.put("2", "22");
properties.put("3", "31");
properties.put("4", "41");
// 迭代器
Enumeration<?> enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
Object key = enumeration.nextElement();
System.out.println(key + ":" + properties.get(key));
}
}
}
4、stringPropertyNames()方式
返回此属性列表中的一组键,其中键及其对应的值为字符串,包括默认属性列表中的不同键,如果尚未从主属性列表中找到相同名称的键。
注意:在此方法中的key和value都需要是String类型的值,如果有一方不是则不会被方法接受。
public class demo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("1", "11");
properties.put("2", "22");
properties.put("3", "31");
properties.put("4", "41");
Set<String> keys = properties.stringPropertyNames();
for (String key : keys) {
System.out.println(key + ":" + properties.get(key));
}
}
}