Properties作为Map集合的使用
1.Properties介绍
- 是一个Map体系的集合类.
- Properties可以保存到流中或从流中加载.
- 属性列表中的每个键及其对应的值都是一个字符串.
Properties的基本使用(示例)
public class PropertiesDemo01 {
public static void main(String[] args) {
//创建集合对象
// Properties<String,String> prop = new Properties<String,String>(); //错误
Properties prop = new Properties();
//存储元素
prop.put("001", "佟丽娅");
prop.put("002", "赵丽颖");
prop.put("003", "刘诗诗");
//遍历集合
Set<Object> keySet = prop.keySet();
for (Object key : keySet) {
Object value = prop.get(key);
System.out.println(key + "," + value);
}
}
}
2.Properties作为Map集合的特有方法
- Object setProperty(String key, String value)
设置集合的键和值,都是String类型,底层调用 Hashtable方法 put - String getProperty(String key)
使用此属性列表中指定的键搜索属性 - Set stringPropertyNames()
从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串
示例代码
public class PropertiesDemo02 {
public static void main(String[] args) {
//创建集合对象
Properties prop = new Properties();
//Object setProperty(String key, String value):设置集合的键和值,都是String类型
prop.setProperty("001", "佟丽娅");
prop.setProperty("002", "赵丽颖");
prop.setProperty("003", "刘诗诗");
//String getProperty(String key):使用此属性列表中指定的键搜索属性
// System.out.println(prop.getProperty("001"));
// System.out.println(prop.getProperty("0011"));
// System.out.println(prop);
//Set<String> stringPropertyNames():从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串
Set<String> names = prop.stringPropertyNames();
for (String key : names) {
// System.out.println(key);
String value = prop.getProperty(key);
System.out.println(key + "," + value);
}
}
}
3.Properties和IO流相结合的方法
- 方法名说明void load(Reader reader)
从输入字符流读取属性列表(键和元素对) - void store(Writer writer, String comments)
将此属性列表(键和元素对)写入此 Properties表中,以适合使用 load(Reader)方法的格式写入输出字符流
示例代码
public class PropertiesDemo03 {
public static void main(String[] args) throws IOException {
//把集合中的数据保存到文件
// myStore();
//把文件中的数据加载到集合
myLoad();
}
private static void myLoad() throws IOException {
Properties prop = new Properties();
//void load(Reader reader):
FileReader fr = new FileReader("myOtherStream\\fw.txt");
prop.load(fr);
fr.close();
System.out.println(prop);
}
private static void myStore() throws IOException {
Properties prop = new Properties();
prop.setProperty("001","佟丽娅");
prop.setProperty("002","赵丽颖");
prop.setProperty("003","刘诗诗");
//void store(Writer writer, String comments):
FileWriter fw = new FileWriter("myOtherStream\\fw.txt");
prop.store(fw,null);
fw.close();
}
}