properties类简介
这个类是util包下的工具类,封装的是map集合,也能够对流进行操作,例如能够实现把集合中的元素存入文件中,也能够文件中的元素读取到集合中。
该类的setproperties只能存入字符类型的key和value,可以看到该方法的调用了map集合的put方法,类似于put方法,但是没有加入泛型
部分代码
public class PropertiesDemo {
@Test
public void propertiesMap(){
Properties properties = new Properties();
properties.put(1, "hello");
properties.put(2, "word");
// 遍历集合
Set<Object> set = properties.keySet();//里面存的是key的值
set.stream().forEach(O-> System.out.println(O));//得到的是key
for (Object key:set){
// 根据key的值去找value
Object value = properties.get(key);
System.out.println("key:"+key+"value:"+value);
}
}
/**
* 测试properties的特殊集合操作
*/
@Test
public void test2(){
Properties properties = new Properties();
// 这里面的key和value只能传入字符串类型的
properties.setProperty("姓名", "小黑");
properties.setProperty("年龄","21");
// 根据姓名找value
String name = properties.getProperty("姓名");//小黑
System.out.println(name);
// 此方法的到的是所有的key的集合
Set<String> set = properties.stringPropertyNames();//{姓名,年龄}
set.stream().forEach(s -> System.out.println(s));
}
/**
* properties的特殊功能,
* A.实现把文件中的键值对存入集合中
* B.实现把集合中的键值对存入文件中
* 应用的方法为:
* A.public void load(Read read);
* B.public void store(Write write, String comment);
*/
@Test
public void load() throws IOException {
Properties properties = new Properties();
properties.load(new FileReader("prop.properties"));
System.out.println(properties);
Set<String> set = properties.stringPropertyNames();
set.stream().forEach(s -> System.out.println(s));
}
@Test
public void story() throws IOException{
Properties properties = new Properties();
properties.setProperty("年龄","18");
properties.setProperty("专业","计算机");
properties.store(new FileWriter("prop.properties"),"这是我的个人介绍");
}
}
人生没有彩排,每天都是现场直播。