读取resources中properties文件内容范例

src/main/resources下test.properties文件内容:(输入中文文件会自动转码)

name=\u674E\u78CA
age=20

src/main/java下ReadProperties.java

package properties;

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

/**
 * 1 建立Properties对象
 * 2 java反射方式获取文件的流
 *   getClass():取得当前对象所属的Class对象
 *   getClassLoader():获取ReadProperties.class的类加载器
 *   Class.getClassLoader().getResourceAsStream(path): 不在同级目录下,也不在子目录下使用这种方法获取资源,最终是由ClassLoader获取资源
 * 3 Properties对象加载资源的流
 * 4 使用键值对的方式获取数据
 * 
 * Title: ReadProperties
 *
 * Description: 
 *
 * @author Ethan
 *
 * @date 2019年6月23日
 *
 */

public class ReadProperties {
    public static void main(String[] args) throws Exception {
        //建立Properties对象
        Properties prop = new Properties();
        //获取文件流
        InputStream ips = ReadProperties.class.getClassLoader().getResourceAsStream("test.properties");
        //加载文件流
        prop.load(ips);
        //获取数据
        String name = prop.getProperty("name");
        String age = prop.getProperty("age");
        System.out.println(name+":"+age);
    }
}

输出结果:

李磊:20

 

posted @ 2019-06-23 15:57  WaterGe  阅读(1839)  评论(0编辑  收藏  举报