posts - 91,  comments - 2,  views - 11万

由于getResource方法在jar和idea中获取的路径不同,按照获取协议区分jar和非jar情况

 resources/application.properties

custom-key=customValue
ReadPropertiesUtil.java
复制代码
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.util.Properties;

public class ReadPropertiesUtil {
    public static void main(String[] args) throws IOException {
        Properties properties = getProperties("application.properties");
        properties.forEach((key, value) -> {
            System.out.println(key + ":" + value);
        });
    }

    /**
     * 获取properties文件
     *
     * @param fileName 文件名
     * @return pro
     */
    public static Properties getProperties(String fileName) {
        Properties properties = new Properties();
        InputStream inputStream;
        try {
            inputStream = getInputStream(fileName);
            properties.load(inputStream);
            return properties;
        } catch (IOException e) {
            System.out.println("read properties error");
        }
        return properties;
    }

    /**
     * 获取resource资源流
     *
     * @return 路径
     */
    private static InputStream getInputStream(String fileName) throws IOException {
        ClassLoader loader = ReadPropertiesUtil.class.getClassLoader();
        // 处理class在根路径下的情况,保证一定存在一个路径
        String className = ReadPropertiesUtil.class.getName().replace('.', '/') + ".class";
        URL url = loader.getResource(className);
        // URL url = ReadPropertiesUtil.class.getResource(""); // class没有包路径时,jar方式获取不到resource
        if (url == null) {
            throw new RuntimeException("unknown resource path");
        }
        String protocol = url.getProtocol();
        System.out.println("protocol:" + protocol);
        if ("file".equals(protocol)) {
            return Files.newInputStream(new File(loader.getResource(fileName).getPath()).toPath());
        } else {
            return loader.getResourceAsStream(fileName);
        }
    }
}
复制代码
 

备注:

idea获取路径:

    file:/X:/fake/target/classes/ReadPropertiesUtil.class

jar执行获取路径:

    jar:file:/X:/fake/target/test.jar!/ReadPropertiesUtil.class

执行效果如下:

idea:

jar包:

java -cp test.jar ReadPropertiesUtil

 

posted on   le.li  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示