您的位置:首页 > 数据库

关于IntelliJ IDEA创建项目无法读取配置文件

2017-05-13 18:21 579 查看
一开始是用JDBC读取外部的数据库配置文件,文件如下:

package hanxiu.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
* JDBC工具类:
* 1) 获取Connection
* 2) 释放资源
*/
public class JDBCUtil {

/**
* 获取Connection
* @return 所获得到的JDBC的Connection
*/
public static Connection getConnection() throws Exception {

/**
* 不建议大家把配置硬编码到代码中
*
* 最佳实践:配置性的建议写到配置文件中
//        String url = "jdbc:mysql:///springdata";
//        String user = "root";
//        String password = "123";
//        String driverClass = "com.mysql.jdbc.Driver";

InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
System.out.print(inputStream);
properties.load(inputStream);

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);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}

/**
* 释放DB相关的资源
* @param resultSet
* @param statement
* @param connection
*/
public static void release(ResultSet resultSet,
Statement statement,
Connection connection){

if(resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

if(statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}

}


一直无法读取到db.properties,报的错误如下



后面通过找资料观查发现才知道文件夹的类型没设置,通过这样设置可以解决问题

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐