import java.io.*;
import java.util.Properties;
import java.util.Set;
public class Demo01Properties {
public static void main(String[] args) throws IOException {
//show01();
//show02();
show03();
}
/*
Load
load(InputStream inStream) 从输入流中读取属性列表(键和元素对)。
load(Reader reader) 按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。
常用步骤:
1.创建Properties集合对象
2.使用Properties集合对象中的方法load读取保存键值对的文件
3.遍历Properties集合
注意:
1.存储键值对的文件中,键与值默认的连接符号可以使用=,空格(其他符号)
2.存储键值对的文件中,可以使用#进行注释,被注释的键值对不会被读取
3.存储键值对的文件中,键与值默认都是字符串,不用再加引号
*/
private static void show03() throws IOException {
Properties prop =new Properties();
prop.load(new FileReader("F:\\basic\\untitled13\\src\\it\\cast\\day15\\demo03\\prop.txt"));//用于字符流
// prop.load(new FileInputStream("F:\\basic\\untitled13\\src\\it\\cast\\day15\\demo03\\prop.txt"));中文不行
Set<String> set = prop.stringPropertyNames();
for (String key : set) {
String value = prop.getProperty(key);
System.out.println(key+"="+value);
}
}
/*
使用步骤:
1.创建Properties集合对象,添加数据
2.创建字节输出流/字符输出流对象,构造方法中绑定要输出的目的地
3.使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
4.释放资源
*/
private static void show02() throws IOException {
//store
//1.创建Properties集合对象,添加数据
Properties prop=new Properties();
prop.setProperty("赵丽颖","168");
prop.setProperty("往事","158");
prop.setProperty("搜索","168");
//2.创建字节输出流/字符输出流对象,构造方法中绑定要输出的目的地
//字符流可以写中文
FileWriter fw=new FileWriter("F:\\basic\\untitled13\\src\\it\\cast\\day15\\demo03\\prop.txt");
//3.使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
prop.store(fw,"save data");
fw.close();
/* prop.store(new FileOutputStream("F:\\basic\\untitled13\\src\\it\\cast\\day15\\demo03\\prop2.txt"),"");
//字节流不能写中文*/
}
/*
使用Properties集合存储数据,遍历取出Properties集合中的数据
Properties集合是一个双列集合,key和value默认都是字符串
Properties集合有一些操作字符串的特有方法
setProperty(String key, String value) 调用 Hashtable 的方法 put。
getProperty(String key) 用指定的键在此属性列表中搜索属性。通过Key找到value值,此方法相当于map集合中的get(key)方法
stringPropertyNames() 返回此属性列表中的键集,其中该键及其对应值是字符串,如果在主属性列表中未找到同名的键,
则还包括默认属性列表中不同的键。此方法相当于Map集合中的KeySet方法
*/
private static void show01() {
//创建Properties集合对象
Properties prop=new Properties();
prop.setProperty("赵丽颖","168");
prop.setProperty("往事","158");
prop.setProperty("搜索","168");
Set<String> set = prop.stringPropertyNames();
for (String s : set) {
String value = prop.getProperty(s);
System.out.println(s+"="+value);
}
}
}