JAVA使用类装载器装载配置文件

这里做的是一个加载数据库配置文件的小示例,可以时时获取到配置 文件的信息。


**注:**db.properties文件必须放在src目录下,否则 NullPointerException


package com.joke.day01;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.junit.Test;

public class Demo1 {
    static String path=null;
    static{
        path=Demo1.class.getClassLoader().getResource("db.properties").getPath();
//取得类加载器并得到加载文件的地址
    }
    @Test
    public Connection getConnection() throws Exception
    {
        InputStream in=new FileInputStream(path);
        Properties proper=new Properties();
        proper.load(in);
        //1、加载驱动
        Class.forName(proper.getProperty("DB_DRIVER"));
        //2、取得连接
         Connection connection=DriverManager.getConnection(proper.getProperty("DB_URL"),proper.getProperty("DB_USER"),proper.getProperty("DB_PASSWORD"));
         if(connection!=null)
         {
             return connection;
         }
         else
         {
             System.out.println("配置信息错误");
             return null;
         }

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值