使用:props.load(DBUtils.class.getClassLoader().getResourceAsStream("day01/db.properties"));
导入配置文件
使用的是反射机制
.class ///获得Class对象
.class.getClassLoader() ///获得ClassLoader对象
.class.getClassLoader().getResourceAsStream(String name); //获得inputStream对象
所以括号里是inputStream对象 这肯定是不变的
///DBUtils.java
package day02;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class DBUtils {
private static String driver;
private static String url;
private static String user;
private static String password;
static{
try{
Properties props = new Properties();
//从类路径中加载文件
props.load(DBUtils.class.getClassLoader().getResourceAsStream("day01/db.properties"));
//props.load(new FileInputStream("db.properties"));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
System.out.println(driver);
System.out.println(url);
System.out.println(user);
Class.forName(driver);
}catch(Exception e){
throw new RuntimeException(e);
}
}
public static Connection openConnection() throws Exception{ //静态方法获得连接
Connection con = DriverManager.getConnection(url,user,password);
return con;
}
}
jdbc 使用properties导入数据库信息2