java读取application.properties文件内容

ε祈祈猫儿з 提交于 2020-10-13 09:58:24

参考文章:jar中资源无法找到报 FileNotFoundException的深度(深入JDK)解析及其终极解决办法

package org.example;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.Properties;

/**
 * @author langpf 2020-09-09 16:02:54
 */
public class ReadPropFileUtil {
    public static void main(String[] args) throws Exception {
        System.out.println("health_assess_data: " + readProp("health_assess_data"));
        System.out.println("lpf: " + readProp("lpf"));
        System.out.println("lpf2: " + readProp("lpf2"));
    }

    private static String readProp(String name) throws IOException {
        Properties prop = new Properties();

        // 获取jar包内部或开发环境中resource文件夹下的文件
        InputStream in0 = ReadPropFileUtil.class.getClassLoader().getResourceAsStream("application.properties");
        prop.load(in0);

        loadCurrPathProp(prop);

        String propVal = prop.getProperty(name);
        if (null == propVal) {
            throw new NullPointerException("read properties key={" + name + "}  is null!");
        }

        return propVal;
    }

    /**
     * 加载 当前工程目录(或jar包所在目录)下的application.properties文件,
     * 且读取该文件优先级较高, 即该文件内容若与jar包内(或工程内)的application.properties文件内容冲突
     * , 则最终读取该文件相应的内容
     *
     * @param prop p
     */
    public static void loadCurrPathProp(Properties prop) throws IOException {
        String osName = System.getProperty("os.name");
        String fileName;
        if (StringUtils.containsIgnoreCase(osName, "Windows")) {
            fileName = System.getProperty("user.dir") + "\\application.properties";
        } else {
            fileName = System.getProperty("user.dir") + "/application.properties";
        }

        File file = new File(fileName);
        if (file.exists()) {
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            prop.load(in);
        }
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!