如何读取jar包外的properties文件和log4j.properties

本文提供了一种灵活加载Log4j配置文件的方法,能够从不同位置读取配置,包括未打包状态、jar包外及jar包内,使得开发者可以在不重新打包的情况下更新配置。

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


时间有限,不做排版和具体讲述问题产生的过程,下面是我的解决方案,已证实有效,其中Log4jP = "log4j.properties"

 

  private void initLog4jProperties()
    {
        //未打包时读取配置
        String file = this.getClass().getClassLoader()
                    .getResource(Log4jP).getFile();
         if(new java.io.File(file).exists())
            {
                 PropertyConfigurator.configure(file);
                    System.out.println("未打包时读取配置");
             return;
            }
            
        //读取jar包外配置文件
         file = System.getProperty("user.dir") +"/conf/"+Log4jP;    
         if(new java.io.File(file).exists())
        {
             PropertyConfigurator.configure(file);
                System.out.println("读取jar包外配置文件");
            return;
        }
        //读取jar包内配置文件
         InputStream in = this.getClass().getClassLoader()
                    .getResourceAsStream(Log4jP);
         Properties p=new Properties();
         try {
            p.load(in);
             PropertyConfigurator.configure(p);
             System.out.println("读取jar包内配置文件");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

             
        
    }



参考内容 如下


转自 http://jrails.iteye.com/blog/1705464


一般在项目中使用properties配置文件的时候都将相关的properties文件放在src目录下,在将该app打包生成jar后,相应的properties配置文件生...

一般在项目中使用properties配置文件的时候都将相关的properties文件放在src目录下,在将该app打包生成jar后,相应的properties配置文件生成在jar包中,这样的话要修改配置文件又要重新打jar包,那是相当的麻烦。 

既然这么麻烦,你肯定想将配置文件放在其他的目录下,生成的jar包内不包含相应的配置文件,修改配置文件无需重新打包,没错,下面就是一种解决方案了。 

读取jar包内配置文件:

  1. InputStream in = this.getClass().getClassLoader().getResourceAsStream("/configfilename.properties"); 

读取jar包外配置文件:

  1. String filePath = System.getProperty("user.dir") + "/conf/configfilename.properties";    
  2. InputStream in = new BufferedInputStream(new FileInputStream(filePath));   

另外,如果app中使用到log4j.properties文件,默认的存放路径是src/log4j.properties,同上面一样,我想把log4j.properties放在其他目录中,这样一来,在修改log4j配置文件的时候无需重新打jar包。 

在main函数第一行添加如下代码:

  1. PropertyConfigurator.configure(System.getProperty("user.dir") + "/conf/log4j.properties"); 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值