[java IO流]之 Properties属性集
Properties属性集
概述:
1.Properties类表示了一个持久的属性集。
2.Properties可以保存在流中或从流中加载;属性列表中每个键及其对应值都是一个字符串。
3.Properties可以当做Map集合类使用
//当成map集合使用
Properties prop=new Properties();
prop.put("Hell01", "Word1");
prop.put("Hell02", "Word2");
prop.put("Hell03", "Word3");
prop.put("Hell04", "Word4");
prop.put("Hell05", "Word5");
Set<Entry<Object,Object>> entrySet = prop.entrySet();
for (Entry<Object, Object> entry : entrySet) {
System.out.print(entry.getKey()+"|");
System.out.println(entry.getValue());
}
//输出结果为:
Hell03|Word3
Hell02|Word2
Hell01|Word1
Hell05|Word5
Hell04|Word4
4.Properties的特殊遍历功能
public Object SetProperty(String key,String value) 添加键值,必须是字符串类型
public String getProperty(String key) 根据键,获取值
public Set stringPropertyNames() 返回键的所有Name
//当成属性集使用
Properties prop=new Properties();
prop.setProperty("Hell01", "Word1");
prop.setProperty("Hell02", "Word2");
prop.setProperty("Hell03", "Word3");
prop.setProperty("Hell04", "Word4");
prop.setProperty("Hell05", "Word5");
Set<String> Keys = prop.stringPropertyNames();
for (String string : Keys) {
String value = prop.getProperty(string);
System.out.println(string+"|"+value);
}
//输出结果为:
Hell03|Word3
Hell02|Word2
Hell01|Word1
Hell05|Word5
Hell04|Word4
Properties和IO流结合使用
public void load(Reader reader) 从字符流读取属性列表(关键字和元素对)
需要创建properties文件
Properties prop=new Properties();
//获取prop.properties文件的键值对,用prop对象接收
prop.load(new FileReader("E:\\java-demo\\day0420\\day0506\\prop.properties"));
Set<String> keys = prop.stringPropertyNames();//遍历
for (String string : keys) {
System.out.print(string);
System.out.println(prop.getProperty(string));
}
//输出结果为:
Hell03Word3
Hell02Word2
Hell01Word1
Hell05Word5
Hell04Word4
public void store(Writer writer,String comments) 将属性列表(键和元素对)写入此properties表中,
步骤:
1.创建properties对象。
2.然后往properties里面添加内容
3.用store方法输入到Properties文件中。
Properties prop=new Properties();
prop.setProperty("Hell01", "Word1");
prop.setProperty("Hell02", "Word2");
prop.setProperty("Hell03", "Word3");
prop.setProperty("Hell04", "Word4");
prop.setProperty("Hell05", "Word5");
prop.store(new FileWriter("E:\\java-demo\\day0420\\day0506\\prop.properties"), "comments");
效果图显示:
配置文件:
1.Properties 轻量级,在网络中传输带宽小,本地存储数据量简单,就是键值对结果,理解为一个类似于map的文件
2.XML 重量级,结构化清晰,可读性强,能够存储复制结构的数据
持久化文件有:
1.txt
2.Properties
3.XML
4.json
5.数据库
本作品采用《CC 协议》,转载必须注明作者和本文链接