1、在java项目中加载路径
在java项目加载文件比较简单,
FileInputStream in = new FileInputStream("./src/jdbc.properties");
因为文件运行时 根目录就是改文件的bin目录
2、在web项目中加载路径
但是在web项目中则不行,因为bin目录是tomcat的bin目录,并且作者在实际学习中发现,MyEclipse 2017中 实际的目录到了C:\Users\***\AppData\Local\MyEclipse 2017 CI
下面,也是比较迷,
具体想看运行目录,可以通过下面这段代码查看
File directory = new File(".");
System.out.println(directory.getCanonicalPath());
此时使用类对象 调用 类路径 就会比较好,当然这个在java项目中也可以
//1)获取类对象
Class clazz = JdbcUtil.class;
/**
* 类路径的根目录
*
* web项目 指向WEB-INF/classes
*/
//2)调用类路径
InputStream in = clazz.getResourceAsStream("/jdbc.properties");
3、附上我的properties数据 以及连接 mysql的工具类代码
url = jdbc:mysql://localhost:3306/表名?characterEncoding=utf8&useSSL=false
user = 用户名
password =用户密码
driverClass =com.mysql.jdbc.Driver
public class JdbcUtil {
private static String url = null;
//jdbc协议+数据库协议+主机地址+端口+连接的数据库
private static String user = null;
private static String password = null;
private static String driverClass = null;
/**
* 使用一次 注册驱动
*/
static{
/**
* 读取jdbc.properties
*/
//创建
Properties prop = new Properties();
//构造
try {
//1)获取类对象
Class clazz = JdbcUtil.class;
/**
* 类路径的根目录
*
* web项目 指向WEB-INF/classes
*/
InputStream in = clazz.getResourceAsStream("/jdbc.properties");
// FileInputStream in = new FileInputStream("./src/jdbc.properties");
//2)加载
prop.load(in);
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
driverClass = prop.getProperty("driverClass");
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 返回数据库连接
* @return
*/
public static Connection getConnection() {
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 释放数据库资源
* @param stmt
* @param conn
*/
public static void close(Statement stmt,Connection conn){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(ResultSet rs, Statement stmt,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}