类加载器从哪里拿到类?配置文件放在哪里?通过配置文件连接数据库

类加载器通过bin目录下拿到类

类加载器获得一个流,类加载器就从bin目录下找文件

写好的配置文件放在src下,又会自动在bin下生成一个配置文件

而我们给用户的工程不包含src,所以当我们加载配置文件时,要通过类加载器,让他去bin下找配置文件。

package com.usc.property;

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

/*
 * 加载properties配置文件
 * IO读取文件,键值对存储到集合中
 * 从集合中以键值对方式获取数据库的连接信息,完成数据库的连接
 */
public class PropertiesDemo {
	public static void main(String[] args)throws Exception {
		//使用类的加载器,获取资源,返回值为InputStream
		InputStream in = PropertiesDemo.class.getClassLoader().getResourceAsStream("database.properties");
		//System.out.println(in);
		Properties prop = new Properties();
		//加载
		prop.load(in);
		//打印配置文件
		//System.out.println(prop);
		//获取集合中的键值对
		String driverClass = prop.getProperty("driverClass");
		String url = prop.getProperty("url");
		String username = prop.getProperty("username");
		String password = prop.getProperty("password");
		Class.forName(driverClass);
		Connection con = DriverManager.getConnection(url,username,password);
		System.out.println(con);
		
		
		
	}
}

你可能感兴趣的:(类加载器从哪里拿到类?配置文件放在哪里?通过配置文件连接数据库)