配置文件的书写和使用(俩种方法)

配置文件一般以.properties为后缀名,例如下面的例子的db.properties

配置文件的书写和使用(俩种方法)_第1张图片

这里的话是要注意等号的左右俩边是不能有空格的

第一种方法

使用的话ResourceBundle类中有一个方法ResourceBundle.getBundle( )是得到配置文件内容的

package cn.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;

public class JDBCUtils {
	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	static {
		ResourceBundle bundle = ResourceBundle.getBundle("db");
		driver = bundle.getString("driver");
		url = bundle.getString("url");
		username = bundle.getString("username");
		password= bundle.getString("password");	
	}
	
	
	
	public Connection getConnection() 
	{
		Connection conn =null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,username,password);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
		
	}
	
	public void Close(Connection conn,PreparedStatement pstmt ,ResultSet rs) 
	{
		try {
			if(rs!=null) {
				rs.close();
			}
			if(pstmt!=null) 
			{
				pstmt.close();
			}
			if(conn!=null) 
			{
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

这里的静态代码块static{  }在类被加载之前就会执行

 

第二种方法

package cn.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

public class JDBCUtils2 {
	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	
	static {
		try {
			//利用classloader来加载properties
			//获得当前对象的类加载器
			ClassLoader loader = JDBCUtils2.class.getClassLoader();
			//通过类加载器获得配置文件的输入流
			InputStream is = loader.getResourceAsStream("db.properties");
			//获得配置文件properties对象
			Properties p = new Properties();
			//获取输入流
			p.load(is);
			driver = p.getProperty("driver");
			url = p.getProperty("url");
			username = p.getProperty("username");
			password = p.getProperty("password");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	
	public Connection getConnection() 
	{
		Connection conn =null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,username,password);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
		
	}
	
	public void Close(Connection conn,PreparedStatement pstmt ,ResultSet rs) 
	{
		try {
			if(rs!=null) {
				rs.close();
			}
			if(pstmt!=null) 
			{
				pstmt.close();
			}
			if(conn!=null) 
			{
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

ps:第一种方式所书写的配置文件只需要写名称,而第二种方式是要将配置文件的全名写入(包括后缀名)

你可能感兴趣的:(配置文件的书写和使用(俩种方法))