通过类加载机制完成。
1.获取到类加载器,调用其获取资源到流的方法
InputStream in = 类.class.getClassLoder().getResourceAsStream(文件)
2.创建Properties对象,加载流到Properties对象中
new Properties().load(in);
3.使用Properties的方法,操作Properties 对象
such:
pro.getProperties(key);
/*
* Properties类表示一组持久的属性。(配置文件)
* Properties可以保存到流中或从流中加载。
* 这个类是线程安全的(加了锁的sychronzied):
* 多个线程可以共享一个Properties对象,而不需要外部同步。
*/
public class PropertiesTest {
public static void main(String[] args) throws IOException {
/*
* 问题:出现空指针异常-->对象未获取成功-->路径错误
* 注意:文件所在位置决定路径的写法
* 在src目录下,只写文件名,其他位置加包名或写全类名
*/
// 读取文件加载配置文件
// 1.利用类加载器,找到配置文件,并装入流中
InputStream inputStream = PropertiesTest.class.getClassLoader()
.getResourceAsStream("properties.properties");
// 2.创建配置properties对象
Properties pro = new Properties();
// 3.加载得到的文件字节流,到Properties对象中
pro.load(inputStream);
// 获取user健对应的值
String property = pro.getProperty("user");
System.out.println(property);
}
}