1 简介
Properties继承自Hashtable,是一组key-value的集合。在Java中,后缀名为properties的文件作为配置文件。同样的后缀为yml的yaml文件同样可以作为配置文件,两者的书写方式有所不同,这里分享一个properties与yml文件互转的在线工具:https://www.toyaml.com/index.html
2 书写规范
基本格式: key=value 或者 key:value,建议使用key=value格式 举个例子: username=root
注释格式: 以#或者!开头的行为注释行,其他位置的都不是注释
3 注意点
3.1 关于空格
① 等号两边的空格不会被读取
② value的末尾处的空格会被读取
③ 如果需要在key中加空格怎么办,空格使用转义字符代替,英文空格为:\u0020,举个例子,
# 配置文件书写
test\u0020key = 123
# Java获取
# 获取配置文件的输入流,getResourceAsStream的参数为db.properties编译后的文件位置
InputStream resourceAsStream = getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
# 获得"test key"的值
String username = properties.getProperty("test key");
3.2 关于换行
① key不能换行
② value可以换行,使用转义字符 \,之后的\t和tab键在获取时会自动去掉举个例子
# properties配置文件(编译后位于/WEB-INF/classes/db.properties)中
username = a\
b\
c\
d\
e\
f
// Java代码
InputStream resourceAsStream = getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
String username = properties.getProperty("username");
System.out.println(username);
> > > abcdef
③ 如果value中有换行想在获取值时也能被获取,那么应该这么些
# properties配置文件(编译后位于/WEB-INF/classes/db.properties)中
username = a\nb\nc\nd\ne\nf
// Java代码
InputStream resourceAsStream = getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
String username = properties.getProperty("username");
System.out.println(username);
> > > .
a
b
c
d
e
f
4 资源文件(xxx.properties)编译后的位置
# 位于java包下的配置文件编译后
/WEB-INF/classes/ + 配置文件所在的源路径
# 位于resources包下的配置文件编译后
/WEB-INF/classes/ + 配置文件所在的源路径