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


時間有限,不做排版和具體講述問題產生的過程,下面是我的解決方案,已證實有效,其中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"); 



發佈了73 篇原創文章 · 獲贊 34 · 訪問量 138萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章