可以结合集合那篇文章一起学习。目标使用Properties集合存储数据,遍历取出Properties集合中的数据
Properties是一个双例集合,Key和Value默认都是字符串。
Properties有操作字符串特有的方法。
serProperties(String key, String value);原理是调用了Hashtable的put方法。
String getProperties(String key) 通过key找到value值,相当于Map集合中的get(key)方法。
Set StringPropertyNames();返回此属性列表中的键,相当于Map中的keySet方法。
public static void show1() {
Properties prop = new Properties();
prop.setProperty("海绵宝宝", "吃蟹黄堡");
prop.setProperty("派大星", "吃巧克力");//设置键和值
Set<String> set = prop.stringPropertyNames();//获取到所有键
for(String key:set) {
String value = prop.getProperty(key);//通过键获取到值
System.out.println(key+"-"+value);
}
}
store(OutputStream out,String comments)
store(Writer writer,String comments)
OutputStream out:字节输出流,不能写中文
Writer write:字符输出流,可以写中文。
String comments:解释说明保存文件是做什么用。一般使用"";
使用步骤
1:对象,添加数据。
2:创建字节FileOutputStream/字符FileWriter输出流对象,构造方法中绑定要输出的目的地
3:使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中
4:释放资源
public static void show2() throws IOException {
Properties prop = new Properties();
prop.setProperty("海绵宝宝", "吃蟹黄堡");
prop.setProperty("派大星", "吃巧克力");//设置键和值
FileWriter fw = new FileWriter("E:\\图片\\b.txt");
prop.store(fw, "data");
fw.close();
//不能写中文
prop.store(new FileOutputStream("E:\\图片\\c.txt"), "data");//匿名对象使用完自动关闭
}
可以使用Properties集合的Load方法,读取硬盘中保存的文件(键值对),读取到集合中使用。
load(FileInputStream in)
load(Reader reader)
使用步骤:
1:创建Properties集合对象
2:使用Properties集合对象中的Load方法读取文件
3:遍历Properties对象。
一般都使用字符流。
public static void show3() throws FileNotFoundException, IOException {
Properties prop = new Properties();
// prop.load(new FileInputStream("E:\\图片\\b.txt"));//按字节读入,会乱码
prop.load(new FileReader("E:\\图片\\b.txt"));//按字符读入,不乱码
Set<String> set = prop.stringPropertyNames();
for(String key:set) {
String value = prop.getProperty(key);
System.out.println(key+"-"+value);
}
}