`

Java读取properties文件工具类

    博客分类:
  • Java
阅读更多
//DB.properties文件
className=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.01:text
name=a
password=a


import java.io.InputStream;
import java.util.Properties;

public class DBProperty {
	private String className;

	private String url;

	private String name;

	private String password;

	private String filePath;

	public String getClassName() {
		return getProperty("className");
	}

	public void setClassName(String className) {
		this.className = className;
	}

	public String getName() {
		return getProperty("name");
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return getProperty("password");
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUrl() {
		return getProperty("url");
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getProperty(String pro) {
		InputStream in;
		Properties p = new Properties();
		try {
			in = Class.forName("com.sailing.DBProperty")
					.getResourceAsStream(this.getFilePath());
			p.load(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return p.getProperty(pro);
	}

}

//使用
         /**
	 * 取得一个数据库连接
	 * 
	 * @return
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public Connection getConnection() throws SQLException,
			InstantiationException, IllegalAccessException,
			ClassNotFoundException {
		DBProperty pro = new DBProperty();
		pro.setFilePath("/DB.properties");
		Connection conn = null;
		// 加载数据库驱动类
		Class.forName(pro.getClassName()).newInstance();
		// 数据库连接URL
		String url = pro.getUrl();
		// 数据库用户名
		String user = pro.getName();
		// 数据库密码
		String password = pro.getPassword();
		// 根据数据库参数取得一个数据库连接
		conn = DriverManager.getConnection(url, user, password);
		return conn;
	}
分享到:
评论
Global site tag (gtag.js) - Google Analytics