由于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 2025-03-02 12:09  le.li  阅读(15)  评论(0)    收藏  举报