properties
在resources文件夹下,建后缀为.properties的文件
文件中,等号前后,不允许有空格
db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/automatic1
user_name=root
password=123456
PropDemo
package day05.jdbc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;
public class PropDemo {
public static void main(String[] args) throws Exception {
//Properties可以理解为k和v都是String的map
//Map<String,String>,这里不需要手动设置泛型,这里默认写死的
Properties properties =new Properties();
// 获取目标文件的方式,方式一
// FileInputStream in =new FileInputStream("src/main/resources/db.properties");
// 方式二,这个方法本身就返回的是InputStream
// 这个方法,会默认去resources下面寻找对应的文件
// 常用方式,就是这个方式二
// 相对于工程目录=》相对于resources 跟目录
InputStream in = PropDemo.class.getClassLoader().getResourceAsStream("db.properties");
// 方式三
// 相对于 PropDemo所在的包的路径
// InputStream in = PropDemo.class.getResourceAsStream("db.properties");
properties.load(in);//传字符流reader或者字节输入流InputStream(读取)
String driver = properties.getProperty("driver");
System.out.println("driver = " + driver);
}
}