目录
步骤
- 创建Properties的实例化对象。
- 通过类加载器创建指向要读取的配置文件的流。
- 将上面创建的流作为参数传入Properties对象的load()函数中。(加载流对应的配置文件)
- 调用Properties对象的getProperty(key)方法读取相应key对应的value。
示例:创建一个.Propertise配置文件,包括四个值:
user=root password=133290
url=jdbc:mysql://localhost:3306/test driver=com.mysql.cj.jdbc.Driver
然后将配置文件信息输出到控制台。
解答
创建配置文件:
当前工程---->src---->右键new---->file---->输入配置文件名.properties
读取并输出配置文件:
@Test
public void test() throws IOException {
//创建Properties类的实例化对象
Properties properties=new Properties();
//通过类加载器创建指向该配置文件的流
InputStream inputStream=PropertiesTest.class.getClassLoader().getResourceAsStream("test.properties");
//将上面创建的流作为参数调用Properties对象的load()方法(加载配置文件)
properties.load(inputStream);
//读取配置文件信息
String user=properties.getProperty("user");
String password=properties.getProperty("password");
String url=properties.getProperty("url");
String driver=properties.getProperty("driver");
//输出配置文件信息
System.out.println("user="+user);
System.out.println("password="+password);
System.out.println("url="+url);
System.out.println("driver="+driver);
}
运行结果如下
user=root
password=133290
url=jdbc:mysql://localhost:3306/test
driver=com.mysql.cj.jdbc.Driver
建议:
读取配置文件在后续会比较常用,建议掌握。