目录结构:
/**
* 获取连接
* @return 返回JDBC得到的Connection
* @throws ClassNotFoundException
*/
public static Connection getConnection() throws ClassNotFoundException, IOException, SQLException {
InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
String url =properties.getProperty("jdbc.url");
String user =properties.getProperty("jdbc.user");
String password =properties.getProperty("jdbc.password");
String driverClass = properties.getProperty("jdbc.driverClass");
Class.forName(driverClass);
return DriverManager.getConnection(url,user,password);
}
debug发现in为空,代码没有写错,只能是没有读取到db.properties文件的内容
第一感觉是resources这个文件加可能有问题,果然,解决方法是:
Files-->Project Structure-->modules-->source 找到resources文件夹,右键选择resourses,右边会出现resource folders
这样就实现了将配置文件添加到classpath,再次debug,不再报空指针,问题解决。