package IO.unit1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
/*1.HashTable的子类,无泛型
*2.键和值都是字符串类型
*3.集合中的数据可以保存到流中,或者从流中获取数据
*通常该集合用于操作以键值对存在的配置文件
*
* */
public class Properties集合 {
public static void main(String []args) throws IOException {
PropertieDemo4();
}
//存储以及修改
public static void PropertieDemo() {
Properties properties=new Properties();
//存储元素
properties.setProperty("zhangsan", "30");
properties.setProperty("lisi", "31");
properties.setProperty("wangwu", "16");
properties.setProperty("zhaoliu", "20");
for(String name:properties.stringPropertyNames()) {
System.out.println(name+":"+properties.getProperty(name));
}
//修改
properties.setProperty("zhaoliu", "100");
for(String name:properties.stringPropertyNames()) {
System.out.println(name+":"+properties.getProperty(name));
}
}
//与流相结合的功能,list操作
public static void PropertieDemo1() {
Properties properties=new Properties();
//存储元素
properties.setProperty("zhangsan", "30");
properties.setProperty("lisi", "31");
properties.setProperty("wangwu", "16");
properties.setProperty("zhaoliu", "20");
properties.list(System.out);
}
//持久化:store
public static void PropertieDemo2() throws IOException {
Properties properties=new Properties();
//存储元素
properties.setProperty("zhangsan", "30");
properties.setProperty("lisi", "31");
properties.setProperty("wangwu", "16");
properties.setProperty("zhaoliu", "20");
FileOutputStream fos=new FileOutputStream("properties.txt");
properties.store(fos, "name+age");
}
//磁盘中已有的键值对信息
public static void PropertieDemo3() throws IOException {
//集合中的数据来自文件,文件中的数据是键值对,
Properties properties=new Properties();
FileInputStream inputStream=new FileInputStream("properties.txt");
properties.load(inputStream);
properties.list(System.out);
}
//对已有的配置文件中的信息进行修改
public static void PropertieDemo4() throws IOException {
//读取文件,并将文件中的键直数据存储到集合中,通过集合修改再通过流存储到文件中
File file=new File("properties.txt");
if(!file.exists()) {
file.createNewFile();
}
FileReader fin=new FileReader("properties.txt");
Properties properties=new Properties();
properties.load(fin);
properties.setProperty("zhangsan", "100000");
FileWriter fileWriter=new FileWriter(file);
properties.store(fileWriter,"");
fileWriter.close();
fin.close();
}
}