java读取配置文件

来源:互联网 发布:淘宝网广场服装夽女士 编辑:程序博客网 时间:2024/06/06 08:29
package cn.ac.siom.db;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Properties;/** * 连接数据库 * @author Administrator * */public class JDBCUtil{private String propertiesfile = "db.properties";public String getPropertiesfile() {return propertiesfile;}public void setPropertiesfile(String propertiesfile) {this.propertiesfile = propertiesfile;}public JDBCUtil(String propertiesfile) {super();this.propertiesfile = propertiesfile;}public JDBCUtil() {super();// TODO Auto-generated constructor stub}public Connection GetConnection() {        Connection con = null;Properties props = new Properties();/*读取配置文件  1 * String pfile = Thread.currentThread().getContextClassLoader().getResource("").getPath()+propertiesfile;System.out.println(pfile);props.load(new FileInputStream(pfile));*/try {//*读取配置文件 方式2InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream(propertiesfile);props.load(in);String drivers = props.getProperty("db.driverClassName");String url = props.getProperty("db.url");try {Class.forName(drivers);con = DriverManager.getConnection(url);System.out.println(con);}catch (ClassNotFoundException e) {System.out.println("连接数据库未找到驱动类:"+e.getMessage());} catch (SQLException e) {System.out.println("连接数据库失败:"+e.getMessage());}} catch (FileNotFoundException e1) {System.out.println(e1.getMessage());} catch (IOException e1) {System.out.println("IO异常,连接失败"+e1.getMessage());}return con;}public boolean closeConn(Connection conn){try {if(!conn.isClosed()){conn.close();System.out.println("disconn");return true;}} catch (Exception e) {System.out.println("断开数据库失败:"+e.getMessage());return false;}return true;}}

0 0