读取properties资源文件中的参数

properties资源文件是放在resource目录下的:

  

新建工具类:

package com.demo.utils;

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

public class PropertyUtil {

    /**
     * 解析properties文件。
     *
     * @param path:properties文件的路径
     * @param key:                 获取对应key的属性
     * @return String:返回对应key的属性,失败时候为null。
     */
    public static String getPropertyByKey(String path, String key) throws Exception {
        String result = null;

        InputStream is = PropertyUtil.class.getClassLoader().getResourceAsStream(path);
        Properties p = new Properties();
        p.load(is);
        result = p.getProperty(key);
        return result;
    }

    public static void main(String[] args) {
        String url = "";
        try {
            url = PropertyUtil.getPropertyByKey("api.properties", "dc_url");
        } catch (Exception e) {
            e.printStackTrace();
            //单文件运行测试时是获取不到资源文件的,需在项目中
            System.out.println("出错啦");
        }
        System.out.println(url);
    }

}

实际项目中引用时,如下:

     String url = "";
        try {
            url = PropertyUtil.getPropertyByKey("api.properties", "dc_url");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("从资源文件获取url时出错", e);
        }

放在其他目录下的资源文件可以参考:https://www.cnblogs.com/yanwenxiong/p/5595255.html

原文地址:https://www.cnblogs.com/mufengforward/p/10721803.html