如何把 className、url、user、password写入资源配置文件中?

来源:互联网 发布:淘宝网休闲女鞋红 编辑:程序博客网 时间:2024/05/17 03:05

一、在当前java工程 src下右键新建 一个file,起名 db.properties ,

双击打开该文件,properties是Map的一个子类,所以配置文件中的数据以键值对形式保存。

如果显示的是文档格式,在文件上 右键 open with - MyEclipse Properties Editor,这样看起来更简洁点。

点击右侧的add添加,key填写String类型的变量名,value填写实际用到的字符串值(如:要连接的url等)。



二、在工具类的ConnOrcl.java中加载配置文件。

第一种方式:在static初始化块中加载,利用当前线程的类加载器中的输入流读进来。

static Properties pros=null;

static{
//加载配置文件
pros = new Properties();

try {
pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}


第二种方式:通过 FileInputStream 读进来。

static

{

try

{

Properties props = new Properties();

FileInputStream in = new FileInputStream("src/oracle.ini");

props.load(in);

in.close();

String drivers = props.getProperty("driver");

String url = props.getProperty("url");

String username = props.getProperty("user");

String password = props.getProperty("pass");

//加载数据库驱动

Class.forName(drivers);

//取得数据库连接

conn = DriverManager.getConnection(url, username, password);

stmt = conn.createStatement();

}

catch (Exception e)

{

e.printStackTrace();

}

}


三、加载驱动,获取连接

//1.加载驱动
try {
Class.forName(pros.getProperty("className"));
} catch (ClassNotFoundException e) {
System.out.println("类找不到");
e.printStackTrace();
}
//2.获取连接
try {
conn = DriverManager.getConnection(pros.getProperty("url"),
pros.getProperty("user"),
pros.getProperty("password"));
} catch (SQLException e) {
System.out.println("获取连接失败");
e.printStackTrace();
}


执行完上述三个步骤,就可以把配置文件读取进来,修改时只需要修改db.properties文件,不需要修改代码,符合OCP原则。



阅读全文
2 0