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

时间:2025-03-24 08:04:00


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

 

  private void initLog4jProperties()
    {
        //未打包时读取配置
        String file = ().getClassLoader()
                    .getResource(Log4jP).getFile();
         if(new (file).exists())
            {
                 (file);
                    ("未打包时读取配置");
             return;
            }
            
        //读取jar包外配置文件
         file = ("") +"/conf/"+Log4jP;    
         if(new (file).exists())
        {
             (file);
                ("读取jar包外配置文件");
            return;
        }
        //读取jar包内配置文件
         InputStream in = ().getClassLoader()
                    .getResourceAsStream(Log4jP);
         Properties p=new Properties();
         try {
            (in);
             (p);
             ("读取jar包内配置文件");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            ();
        }

             
        
    }



参考内容 如下


转自 /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("/"); 

读取jar包外配置文件:

  1. String filePath = ("") + "/conf/";    
  2. InputStream in = new BufferedInputStream(new FileInputStream(filePath));   

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

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

  1. (("") + "/conf/");