您的位置:首页 > 编程语言 > Java开发

java读取properties配置文件

2015-12-08 17:58 621 查看
一:在项目资源包src、config下新建dbconfig.properties文件

driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
user=pwd
password=pwd


二:创建连接类

package uaap.webservice.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

import cn.com.pansky.usp4o.common.util.Debug;

public class JDBCConnection {
private Connection conn = null;

/**
* 建立连接(方式1)
*/
public Connection getConnect(){
try {
Map map =getConnectProperties();
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
String driver = null;
String url = null;
String user = null;
String password = null;
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
//		   System.out.println("" + entry.getKey() + ":" + entry.getValue());
if(entry.getKey().equals("driver")){
driver=entry.getValue();
}else if (entry.getKey().equals("url")){
url=entry.getValue();
}else if(entry.getKey().equals("user")){
user=entry.getValue();
}else if(entry.getKey().equals("password")){
password=entry.getValue();
}
}
//连接
Class.forName(driver);
conn=DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}

/**
* 获取数据连接属性
* @return key-value
*/
public static  Map<String, String> getConnectProperties() {
Map<String, String> map = new HashMap<String, String>();
InputStream in = JDBCConnection.class.getClassLoader()
.getResourceAsStream("dbconfig.properties");
Properties prop = new Properties();
try {
prop.load(in);
Enumeration<?> allName = prop.propertyNames();
while (allName.hasMoreElements()) {
String name = (String) allName.nextElement();
String value = (String) prop.get(name);
Debug.println("===================="+name + ":" + value);
map.put(name, value);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}

//===================================================================================

/**
* 建立JDBC连接(方式2)
*/
public Connection getConnection() {
ResourceBundle bundle = ResourceBundle.getBundle("dbconfig");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
Connection 	conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: