属性配置文件的使用方法

http://www.itjxue.com  2015-07-17 01:12  来源:未知  点击次数: 

属性配置文件的使用方法
我们常常使用配置文件来进行工程属性的配置,那么我们如何使用我们的属性文件呢?
假设有一个连接数据库的属性配置文件jdbc.properties,
文件内容如下:
jdbc.driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
jdbc.url=jdbc:microsoft:sqlserver://10.0.0.168:1433;
jdbc.username=sa
jdbc.password=sa
jndi.databaseName=northwind

那么如何使用配置文件呢?其实很简单
我们创建如下类:
/*
 * Created on 2005-8-15
 *This  class  is  created  to  test  the  using  of   the  properties  file
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package zy.pro.wd.demo;


import java.io.FileInputStream;
import java.util.Properties;

public class PropertiesDemo {

    /**
     *
     */
    public PropertiesDemo() {
        super();
        // TODO Auto-generated constructor stub
    }
    public  void  testPropertiesFile(){
        try{
            Properties pro = new Properties();

            pro.load(new FileInputStream("src/jdbc.properties"));
            System.out.println(pro.getProperty("jdbc.driver"));
            System.out.println(pro.getProperty("jdbc.url"));

        }catch(Exception  e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        PropertiesDemo  pd=new PropertiesDemo();
        pd.testPropertiesFile();
    }
}

粗体部分是主要部分,通过load()方法来加载配置文件,然后通过getProperty()方法来取得配置文件中的属性。
注意:取得配置文件的相对路径一定要正确,否则,将会抛出找不到文件的异常。我的配置文件路径如下图:


程序输出结果如下:
com.microsoft.jdbc.sqlserver.SQLServerDriver
jdbc:microsoft:sqlserver://10.0.0.168:1433;
此程序在Eclipse3.0下调试通过。

(责任编辑:IT教学网)

更多

推荐java认证文章