IDEA使用问题之getResourceAsStream读取配置文件失败

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LuuvyJune/article/details/81904662

目录结构:

/**
     * 获取连接
     * @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,不再报空指针,问题解决。

猜你喜欢

转载自blog.csdn.net/LuuvyJune/article/details/81904662