Properties集合
java.util.Properties
类继承HashTable
- 表示一个持久的属性集;
- 可保存在流中或从流中加载,每一个键值都是字符串,是一个双列集合;
- 它是唯一一个跟IO流相结合的集合;
- 可以使用store()方法把集合中的临时数据,持久化写入硬盘中存储;
- 可以使用load()方法把硬盘中保存的键值对,读取到集合中使用;
常用方法
- public Object setProperty(String key, String value) : 保存一对属性。底层就是put()方法;
- public String getProperty(String key) :使用此属性列表中指定的键搜索属性值,相当于get()方法;
- public Set stringPropertyNames() :所有键的名称的集合,相当于keySet()方法;
简单应用
public static void main(String[] args) {
Properties prop = new Properties();
//添加数据
prop.setProperty("fileName","a.txt");
prop.setProperty("length","10000");
prop.setProperty("location","demo\\propertiesDemo");
//获取所有key的集合
Set<String> names = prop.stringPropertyNames();
//遍历集合,使用getProperty方法获取value
for (String name : names) {
String value = prop.getProperty(name);
System.out.println(name +"--"+ value);
}
}
IO案例
- 可以使用store()方法把集合中的临时数据,持久化写入硬盘中存储;
注意: - void store(OutputStream out,String comments) OutputStream out:字节输出流,不能写中文;
- void store(Writer writer,String comments) Writer writer:字符输出流,可以写中文;
- comments:注释,用来解释说明保存的文件是干什么的,不能使用中文,会产生乱码,默认是unicode编码,一般使用空字符串;
public static void main(String[] args) {
Properties prop = new Properties();
//添加数据
prop.setProperty("fileName","a.txt");
prop.setProperty("length","10000");
prop.setProperty("location","demo\\propertiesDemo");
//创建FileWriter对象
try(FileWriter writer = new FileWriter("src\\demo\\propertiesDemo\\a.txt")) {
//使用store写入磁盘
prop.store(writer,"");
}catch (IOException e){
e.printStackTrace();
}
}
- 可以使用load方法从硬盘中将源数据读取到集合中;
注意: - void load(InputStream input):字节输入流,不能读取含有中文数据;
- void load(Reader reader):字符输入流,可以读取含有中文的数据;
public static void main(String[] args) {
//创建集合对象
Properties prop = new Properties();
try (FileReader reader = new FileReader("src/demo/propertiesDemo/a.txt")){
//使用load方法读取文件
prop.load(reader);
//遍历集合
Set<String> keys = prop.stringPropertyNames();
for (String key : keys) {
String value = prop.getProperty(key);
System.out.println(key+"="+value);
}
}catch (IOException e){
e.printStackTrace();
}
}