属性集
5.1 概述
java.util.Properties 继承于Hashtable ,来表示一个持久的属性集。它使用键值结构存储数据,每个键及其对应值都是一个字符串。该类也被许多Java类使用,比如获取系统属性时,System.getProperties 方法就是返回一个Properties对象。
java.util.Propertise集合 extends Hashtable implements Map
Properties集合是一个唯一和IO流相结合的集合
可以使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
可以使用Properties集合中的方法load,把硬盘中保存的文件(键对值),读取到集合中
属性列表中的每个键对值及其对应的值都是一个字符串
properties集合是一个双列集合,key和value默认的都是字符串
5.2 Properties类
构造方法
public Properties() :创建一个空的属性列表。
基本的存储方法
public Object setProperty(String key, String value) : 保存一对属性。
public String getProperty(String key) :使用此属性列表中指定的键搜索属性值。
public Set stringPropertyNames() :所有键的名称的集合。
public static void main(String[] args) {
// 创建Properties集合对象
Properties prop = new Properties();
// 使用setProperty往集合中的添加数据
prop.setProperty("迪丽热巴","170");
prop.setProperty("古力娜扎","167");
prop.setProperty("霹雳科碴","190");
// prop.put(1,true); 写什么类型都可以
// 使用stringPropertyNames把properties结合中的键取出,存储到一个set集合中
Set set = prop.stringPropertyNames();
// 遍历set集合,取出properties集合中的每一个键
for (String key : set) {
// 使用getProperties方法通过key获取value
String value = prop.getProperty(key);
System.out.println(key+"="+value);
}
}
store方法(键值对写如硬盘)
可以使用properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
void store (OutputStream out,String comments)
void store(Write writem,String comments)
参数:
OutputStream out:字节输出流,不能写入中文
Write write:字符输出流 可以写中文
String comments:注释,用来解释说明保存的文件是做什么的
不能使用中文,会产生乱码,默认是Unicode编码
一般使用" " 空字符串
使用步骤:
创建Properties集合的对象,添加数据
创建字节输出流/字符输出流对象,构造方法中绑定要输出的目的地
使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
释放资源
Load(键值对读取到内存)
使用Properties集合中的方法Loda,把硬盘中的文件(键值对),读取到集合中使用
void Load(InputStream inStream)
void Load(Reader reader)
参数:
InputStream inStream:字符输入流,不能读取含有中文的键值对
Reader reader:字符输入流,能读取含有中文的键值对
使用步骤:
创建Properties集合的对象
使用Properties集合中的方法Load,读取键值对文件
遍历properties集合
注意:
存储键值对的文件中,键于值默认的连接符号可以使用 = ,空格(其他符号)
存储键值对的文件中,可以使用#进行注释,备注注释的文件不能读取
存储键值对的文件中,键于值默认的都是字符串,不用加引号
public static void main(String[] args) throws IOException {
// 创建Properties集合对象
Properties prop = new Properties();
// 2. 使用Properties集合中的方法Load,读取键值对文件
prop.load(new FileReader("D:\Test\f.txt"));
// 3. 遍历properties集合
Set set = prop.stringPropertyNames();
for (String key : set) {
String value = prop.getProperty(key);
System.out.println(key+"="+value);
}
}