当前位置: 移动技术网 > IT编程>开发语言>Java > Java读取.properties配置文件

Java读取.properties配置文件

2018年10月17日  | 移动技术网IT编程  | 我要评论

一、介绍

properties文件在java中主要为配置文件,文件类型为:.properties,格式为文本文件,内容格式为"键=值"

二、读取

这里我采用的是getresourceasstream的文件读取方法

如果想要使用这个方法,则需要了解一些基本使用信息:

1、读取文件路径范围:只局限于工程的源文件中

2、文件访问形式:带"/"是绝对路径,不带"/"是相对路径

3、读取文件类型:主要为:.properties文件,.xml文件

三、使用

主要方法有:

1、 load ( inputstream  instream) :从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如的 beans.properties 文件)进行装载来获取该文

件中的所有键 - 值对。

2、 setproperty ( string  key, string  value) :调用 hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

3、 getproperty ( string  key) :用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

4、 store ( outputstream  out, string  comments) :以适合使用 load 方法加载到 properties 表中的格式,将此 properties 表中的属性列表(键和元素

对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

5、 clear ():清除所有装载的 键 - 值对。该方法在基类中提供。



java项目配置文件存放位置:

maven项目配置文件存放位置:

 

配置文件:

classname = edu.nf.ch02.impl.sub

 

java代码:

public class main {

    public static void main(string[] args) throws ioexception {
        //创建properties对象
        properties prop = new properties();
        //读取classpath中的properties文件
        prop.load(main.class.getclassloader().getresourceasstream("bean.properties"));
        //根据键取出值
        string classname = prop.getproperty("classname");
        system.out.println(classname);
        
    }
}

运行结果:

 

封装的propertiesutil工具类:

public class propertyutil {

    private static properties prop = new properties();

    static {
        try {
            prop.load(propertyutil.class.getclassloader().getresourceasstream("calculator.properties"));
        } catch (ioexception e) {
            throw new runtimeexception(e.getmessage());
        }
    }

    /**
     * 根据name获取property
     * @param name
     * @return
     */
    public static string getproperty(string name) {
        return prop.getproperty(name);
    }

    /**
     * 获取所有的property
     * @return
     */
    public static list<string> getbeanfactoryclass() {
        list<string> list = new arraylist<>();
        set<string> keys = prop.stringpropertynames();
        for (string key : keys) {
            list.add(prop.getproperty(key));
        }
        return list;
    }
}

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网