读取properties配置文件的方法

一般在.properties文件中配置数据库连接的相关信息,我们需要从中读取信息,以便建立与数据库的连接。

文件目录:

application.properties配置信息:

url=jdbc:oracle:thin:@localhost:orl
driverName=oracle.jdbc.driver.OracleDriver 
username=scott 
password=tiger

我们需要在java文件中读取application.properties中的配置信息:

1.getResourceAsStream获取资源文件,使用load方法加载资源文件,得到Properties类。

package com.xuhui;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MainApp {
    public static void main(String[] args){
        Properties properties = new Properties();
        InputStream in =  MainApp.class.getResourceAsStream("/application.properties");//加载 application.properties资源文件,如果该文件在包内则加包名
        try {
            properties.load(in);
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.print(properties.getProperty("driverName"));//获取application.properties中的driverName信息
        
    }
}

 2.ResourceBundle中getBundle获取资源文件。

package com.xuhui;

import java.util.ResourceBundle;

public class MainApp {
    public static void main(String[] args){
        ResourceBundle bundle = ResourceBundle.getBundle("application");//读取application.properties文件,不加.properties后缀,不加路径名
        System.out.print(bundle.getString("driverName"));//获取资源文件信息
    }
}
posted @ 2016-08-15 12:56  JokerPig  阅读(4636)  评论(0编辑  收藏  举报