这里做的是一个加载数据库配置文件的小示例,可以时时获取到配置 文件的信息。
**注:**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;
}
}
}