读取.properties配置文件的方式

一.Properties类解读:

1.Properties类本质其实还是HashTabe,及底层的实现是HashTable

public
class Properties extends Hashtable<Object,Object>

 可以看到Properties继承了HashTable类,HashTable底层是以数组+链表的形式实现的(jdk1.7,jdk1.8就变成了数组+链表+红黑树的结构);HashTable这种数据结构中可以存放很多种数据类型,但是Properties类只支持存储String类型的key/value,有api文档为证:

2. 所以Properties类中不建议使用父类HashTable中的put/putAll方法,因为这有可能会插入一些非字符串的键值,以api问档为证(其实我就是翻译了一遍文档):

 3.Properties类可以从流中读取或者保存到流中。

 上api:

 

 

二.

方式一:直接使用流的方式加载properties文件

package com.tust.test.properties;

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

public class PropertiesTest {
    public static void main(String[] args) {
        try {
            Properties properties = new Properties();
            /*
            当使用IO流来加载properties文件的时候
            FileInputStream fis = new FileInputStream("propertiesTest1.properties");来读取文件的时候,默认是在当前module(当前工程下)下查找该properties文件;
            当然如果properties属性文件不在当前模块下的时候,可以指定具体的路径:
            FileInputStream fis = new FileInputStream("src\resources\propertiesTest1.properties");
            */
            //FileInputStream fis = new FileInputStream("propertiesTest1.properties");
            FileInputStream fis = new FileInputStream("src\resources\propertiesTest1.properties");
            properties.load(fis);
            System.out.println(properties.getProperty("name"));
            System.out.println(properties.getProperty("age"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方式二:使用反射加载properties配置文件

package com.tust.test.properties;

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

public class PropertiesTest {
    public static void main(String[] args) {

        try {
            Properties properties = new Properties();
            /*
            当时用类加载器去加载properties属性文件的时候,默认在是在当前module(当前项目)的src下;
            如果属性文件不在src下,比如是在src/resources下,那么使用:
            InputStream resourceAsStream = PropertiesTest.class.getClassLoader().getResourceAsStream("src\resorces\propertiesTest1.properties");就不行
            */
            InputStream resourceAsStream = PropertiesTest.class.getClassLoader().getResourceAsStream("propertiesTest1.properties");
            properties.load(resourceAsStream);
            System.out.println(properties.getProperty("name"));
            System.out.println(properties.getProperty("age"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

配置文件不建议写在当前module(项目下),建议写在src下,如果使用方式一,那么应该在路径前添加src\,如果使用方式二则不必。

原文地址:https://www.cnblogs.com/wsxdev/p/11661145.html