java可以通过Properties类来加载配置文件,该全限定名是java.util.Properties .
public synchronized void load(InputStream inStream) throws IOException通过该方法来加载配置文件
使用public String getProperty(String key) 方法来获得配置文件中的字段
下面是一段加载数据库的配置文件的一段代码
package com.dao;
import java.sql.Statement;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DaoImpl {
private String driver;//驱动
private String url;//数据库路径
private String user;//用户
private String password;//用户密码
//初始化数据库
public void initDataBase(String param) throws FileNotFoundException, IOException{
//产生配置文件类
Properties pro = new Properties();
//加载配置文件
pro.load(new FileInputStream(param));
//获取配置
driver = pro.getProperty("driver");
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
}
//执行sql查询语句
public void executedSql(String sql,int i ) throws SQLException, ClassNotFoundException{
long start = System.currentTimeMillis();
//加载数据库驱动
Class.forName(driver);
//获取链接
Connection conn = DriverManager.getConnection(url,user,password);
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(sql);
while(result.next()){
System.out.println(result.getString(1) + "\t" + result.getString(2));
}
long end = System.currentTimeMillis();
System.out.println("the " + i + " times lasts time : " + (end - start));
}
public static void main(String[] args)
throws FileNotFoundException, IOException, SQLException, ClassNotFoundException{
DaoImpl dao = new DaoImpl();
dao.initDataBase("G:/mysqlx.properties");
for(int i = 0 ; i < 100; i++){
dao.executedSql("select * from student",i);
}
}
}