服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

使用properties从配置文件中读取数据

    本文简单介绍如何使用properties类从文本文件中读取我们实现定义好的key-value格式的数据,这些数据可以作为软件的配置文件,当然如果你是开发更为复杂的软件的话,那么你应该使用xml作为元数据的存储方式,因为它更为强大。

    当我们开发数据库系统的时候,我们要通过jdbc连接数据库,这个时候我们可能会写出这样的类似代码
public class basicconnection {

    private string dbdriver;
    private string dburl;
    private string dbuser;
    private string dbpassword;

    public static void main(string args[]) {
      
    }

    public basicconnection {
        init();
    }

    private void init() {
       try {

            // set the properties
            this.dbdriver = "oracle.jdbc.driver.oracledriver";
            this.dburl = "jdbc:oracle:thin:@127.0.0.1:1521:dev2";
            this.dbuser = "monkey";
            this.dbpassword = "password";

            // load the driver
            class.forname(dbdriver);

        } catch (exception e) {
            throw new runtimeexception("unable to init, exiting...");
        }
    }

    private connection getconnection()
        throws sqlexception {
        return drivermanager.getconnection(dburl, dbuser, dbpassword);
    }

}
这样的代码,工作起来没有什么问题。但是他存在的缺点就是dbdriver等属性都是硬编码的,当你的数据库的地址改变,用户名改变的情况下,这个代码就不能正常的工作了。你必须重新编译这个代码。

    在java.util包内有一个properties类,他扩展了hashtable。可以用来存储类似于上述情况的数据。你必须要准备一个文本文件,比如config.props,在文件里面写好你要配置的数据。例如
dbdriver=oracle.jdbc.driver.oracledriver
dburl=jdbc:oracle:thin:@127.0.0.1:1521:dev2
dbuser=monkey
dbpassword=password

使用properties类非常的简单,你只需要首先把这个文件转换成inputstream,然后调用properties的成员方法load(inputstream is),这样就把数据设置好了,当我们要读取的时候使用getproperty(string key)就可以了,返回值为string类型。注意properties只能存储string类型的对象。
这样我们就可以提供一个新的方法来读取文件中的数据了,而不是使用硬编码的方式。下面给出改进后的程序
private void init() {
        try {
            string propsfilename = "config.props";
            inputstream is = getclass().getresourceasstream(propsfilename);
            properties p = new properties();
            p.load(is);

            // set the properties
            this.dbdriver = p.getproperty("dbdriver");
            this.dburl = p.getproperty("dburl");
            this.dbuser = p.getproperty("dbuser");
            this.dbpassword = p.getproperty("dbpassword");

            // load the driver
            class.forname(this.dbdriver);

        } catch (exception e) {
            throw new runtimeexception("unable to initialize, exiting...");
        }
    }
这样我们只需要修改配置文件就可以了,没有必要再修改源代码。

扫描关注微信公众号