java读取property文件

property文件中:

     

   url = jdbc:mysql://localhost:3306/resume
   user= root
   pwd = 123

java代码读取:

 

     

package com.util;

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

 

public class DBUtil {

//建立连接
public static Connection getConnection() throws Exception {
Connection conn = null;
String property=getProperty();
String[] propertys=property.split(" ");


String url = propertys[0];
String user = propertys[1];
String pwd = propertys[2];

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
e.printStackTrace();
throw e;
}

return conn;
}

//获取property的配置文件
public static String getProperty()
{
Properties pro= new Properties();
String property="";
try
{
InputStream is = DBUtil.class.getResourceAsStream("../../config.property");
pro.load(is);
String url = pro.getProperty("url").trim();
String user = pro.getProperty("user").trim();
String pwd = pro.getProperty("pwd").trim();
property=url+" "+user+" "+pwd;
if(is!=null) is.close();
}catch(Exception e) {
System.out.println("there is error to read config file...");
e.printStackTrace();
}
return property;
}

}

 

posted @ 2013-11-03 21:18  一步一个脚印coding  阅读(1585)  评论(0编辑  收藏  举报