IO流--与properties集合配合使用
IO流--与properties集合配合使用:
注:生产上主要用于常量文件的配置,读取常量文件;
1:properties集合的放值与取值:
/*
* properties集合继承自hashTable,使用properties父类的放值(put();),取值(get();)
* 功能,遍历集合得到的是Object类型的;
* 所以我们使用properties自己特有的放值(setProperties();)和取值(getProperties();)的功能
* 遍历集合得到的是String类型的;
*/
@Test
public void test() throws IOException {
Properties properties = new Properties();
properties.setProperty("张三","23");
properties.setProperty("李四","25");
properties.setProperty("王二","29");
//properties父类的遍历:
// Set<Object> objects = properties.keySet();
// for(Object key:objects){
// Object value = properties.get(key);
// System.out.println(key +"="+value);
// }
//使用自身的方法遍历:
Set<String> strings = properties.stringPropertyNames();
for(String key :strings){
String value = properties.getProperty(key);
System.out.println(key+"="+value);
}
}
2:从properties集合写入参数到文件:
public void propertiesWrite() throws IOException {
Properties properties = new Properties();
properties.setProperty("张三","23");
properties.setProperty("李四","25");
properties.setProperty("王二","29");
Writer writer = new FileWriter("OnlyFileTest/properties.txt");
properties.store(writer,"文件说明(注释)");
writer.close();
}
3:从文件中读取键值对的参数到properties集合中:
public void propertiesRead() throws IOException {
Reader fileReader = new FileReader("OnlyFileTest/properties.txt");
Properties properties = new Properties();
properties.load(fileReader);
fileReader.close();
System.out.println(properties);
}