java项目中设置 System.getProperty(“XXX”)自定义变量

本文介绍了一种在Java中加载和解析配置文件的方法,通过使用Properties类从不同路径读取配置信息,并处理可能的异常情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

 public static void main(String[] args) {
        String property = System.getProperty("config-dir");
        // D:\开源项目\demo_project\jfengTestProject01\src\main\resources\solver\config.properties
        Properties configProperties = getConfigProperties(property+"\\solver\\config.properties", false);
        System.out.println(configProperties);
    }

  private static Properties getConfigProperties(String confFilePath, boolean cp){
        Properties configProperties;
        configProperties = new Properties();
        InputStream is = null;
        String path = confFilePath;
        try{
            if(cp) {
                is = getResourceAsStream(confFilePath);
                path = getResource(confFilePath).toString();
            }else {
                is = new FileInputStream(confFilePath);
            }
            log.info("loading configruation from "+path);
            configProperties.load(is);
        }catch(IOException e){
            throw new RuntimeException("failed to load configuration from "+confFilePath);
        }finally {
            if(is != null) {
                try{is.close();}catch(IOException e) {log.error("failed to close input stream of "+path, e);}
            }
        }
        if(configProperties.isEmpty()){
            log.warn("nothing loaded from "+path);
        }
        return configProperties;
    }

    public static InputStream getResourceAsStream(String path){
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(path);
        if(is == null){
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
        }
        if(is == null) {
            throw new RuntimeException("resouce file not found. "+path);
        }
        return is;
    }

    public static URL getResource(String path){
        URL url = ClassLoader.getSystemClassLoader().getResource(path);
        if(url == null){
            url = Thread.currentThread().getContextClassLoader().getResource(path);
        }
        if(url == null) {
            throw new RuntimeException("resouce file not found. "+path);
        }
        return url;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值