Properties 工具类 和 ResourceBundle 工具类(接上一篇JavaIO包)
2 Properties 工具类
2.1 Properties集合的基本使用
java.util.Properties集合 extends Hashtable<k,v> implements Map<k,v>双列集合
1、Properties 类表示了一个持久的属性集
Properties 可保存在流中或从流中加载
Properties集合是一个唯一和IO流相结合的集合
我们可以使用Properties集合中的方法store,把集合中的临时数据,持久化到硬盘中存储(内存–>硬盘)
我们可以使用Properties集合中的方法load,把硬盘文件中保存的键值对,读取到内存中集合里边使用(硬盘–>内存)
2、属性列表中每个键及其对应值都是一个字符串
Properties是一个双列集合,不需要写泛型,key和value默认都是字符串String类型
3、Properties集合的基本使用
使用Properties集合存储数据,遍历集合获取集合中的元素,因为Properties集合健和值默认都是String类型,所以集合中有一些和String相关的特有的方法
- Object setProperty(String key, String value) 往Properties集合中添加键值对,相当于Map集合的put方法
- String getProperty(String key) 根据key获取value,相当于Map集合的get(key)方法
- Set< String > stringPropertyNames() 返回此属性列表中的键集,相当于Map集合的keySet方法
2.2 Properties集合中的方法store
我们可以使用Properties集合中的方法store,把集合中的临时数据,持久化到硬盘中存储(内存–>硬盘)
void store(OutputStream out, String comments)
void store(Writer writer, String comments)
方法的参数:
- OutputStream out:传递字节输出流,不能写中文,会出现乱码,可以传递OutputStream的任意子类对象
- Writer writer:传递字符输出流,能写中文,不会出现乱码,可以传递Writer的任意的子类对象
- String comments:注释解释说明我们保存文件是做什么用的,一般传递"",注释不能写中文,默认使用Unicode编码,写中文会出现乱码
使用步骤:
- 1.创建Properties集合对象,往集合中添加数据
- 2.使用Properties集合中的方法store,把集合中的临时数据,持久化到硬盘中存储
public class Demo02Properties {
public static void main(String[] args) throws IOException {
//1.创建Properties集合对象,往集合中添加数据
Properties prop = new Properties();
prop.setProperty(<