关于.class.getClassLoader().getResourceAsStream

从配置文件读取获得连接mysql数据库的代码中,有这么一段

InputStream in=JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
Properties pro = new Properties();
pro.load(in);

其中
JDBCUtilsConfig.class是获得当前对象所属的class对象
getClassLoader()是取得该Class对象的类装载器
getResourceAsStream(“database.properties”) 调用类加载器的方法加载 资源,返回的是字节流
使用Properties类是为了可以从.properties属性文件对应的文件输入流中,加载属性列表到Properties类对象,然后通过getProperty方法用指定的键在此属性列表中搜索属性

完整代码如下:

public class JDBCUtilsConfig {
    private static Connection con;
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;

    static{
        try{
            readCongig();
            Class.forName(driverClass);
            con =DriverManager.getConnection(url, username,    password);
        }catch(Exception ex){
            throw new RuntimeException("数据库连接失败");
        }

    }
     private static void readCongig() throws IOException {

     InputStream in=JDBCUtilsConfig..class.getClassLoader().getResourceAsStream("database.properties");

        Properties pro = new Properties();
        pro.load(in);
        driverClass=pro.getProperty("driverClass");
        url= pro.getProperty("url");
        username=pro.getProperty("username");
        password = pro.getProperty("password");
    }
    public static Connection getConnection() {
        return con;
    }   
}

猜你喜欢

转载自blog.csdn.net/wsad578169903/article/details/68160377
今日推荐