在项目中,我们经常会将数据通过键值对的形式封装到properties配置文件中。通常我们会将配置文件放在项目src目录。
此案例配置文件信息:
文件名:config.properties
文件内容:username=zhangsan
password=123
一、类加载器
注意:这种方式书写文件名称需要加上.properties
// 通过本类的类加载器得到输入流
InputStream in = PropertiesDemo.class.getClassLoader().getResourceAsStream("config.properties");
// 创建Properties对象
Properties prop = new Properties();
// 将输入流加载今properties
prop.load(in);
// 获取配置文件中的数据
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println("username:" + username);
System.out.println("password:" + password);
运行截图
二、ResourceBundle
注意:通过ResourceBundle只能读取后缀名为properties的文件,所以不需要书写.properties
// 创建ResourceBundle对象并加载配置文件
ResourceBundle bundle = ResourceBundle.getBundle("config");
// 获取配置文件中的数据
String username = bundle.getString("username");
String password = bundle.getString("password");
System.out.println("username:" + username);
System.out.println("password:" + password);
运行截图