Properties
Properties
Properties 属性映射:是一种存储键值对的数据结构,在java中用来存储配置信息
特性:
- 继承自
Hashtable
,每个键及其对应值都是一个字符串 - 映射可以很容易的存入文件以及从文件中加载
- 有一个二级表保存默认值
- 该类也被许多Java类使用,比如获取系统属性时,
System.getProperties
方法就是返回一个Properties
对象
Properties集合是唯一一个与IO流相结合的集合
包路径
1 | java.util |
常用方法
- Properties集合是一个双列集合,key和value默认都是字符串
- Properties集合有一些操作字符串的特有方法
1
2
3
4
5
6
7
8
9
10
11public Object setProperty(String key,String value)
//设置键值
public String getProperty(String key)
//通过key找到value值,用指定的键在此属性列表中搜索属性,相当于Map集合中的get方法
public String getProperty(String key,String defaultValue)
//当找不到key值时,会返回设置的默认值
public Set<String> stringPropertyNames()
//返回此属性列表中的键集,其中该键及其对应值是字符串,相当于Map集合中的keySet方法
1 | Properties prop = new Properties(); |
store方法
1 | public void store(Writer writer,String comments)throws IOException |
步骤:
- 创建Properties集合对象
- 使用
setProperty()
方法存入键值对 - 创建字节/字符流对象
- 使用Properties集合中的方法
store
,把集合中的临时数据持久化写入到硬盘中存储 - 释放资源
示例代码
1 | Properties prop = new Properties(); |
运行后的a.txt文件,会自动加一个时间
1 | #Settings |
load方法
1 | public void load(Reader reader)throws IOException |
步骤:
- 创建Properties集合对象
- 创建字符/字节输入流
- 使用Properties集合对象中的方法
load
读取保存键值对的文件 - 遍历Properties集合
1 | Properties prop = new Properties(); |
注意:
- 存储键值对的文件中,键与值默认的连接符号可以使用 -,空格(其他符号)
- 存储键值对的文件中,可以使用#进行注释,被注释的键值对不会再被读取
- 存储键值对的文件中,键与值默认都是字符串,不用再加引号
System中的Properties
方法
1 | Properties getProperties() |
例子
1 | Properties properties = System.getProperties(); |
缺点
- 某些操作系统没有主目录的概念,所以很难找到一个统一的配置文件位置
可以用System.out.println(System.getProperties().getProperty("user.home"));
来获取用户主目录
- 关于配置文件的命名没有标准约定,用户安装多个java应用时,很容易发生命名冲突