時間有限,不做排版和具體講述問題產生的過程,下面是我的解決方案,已證實有效,其中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包內配置文件:
- InputStream in = this.getClass().getClassLoader().getResourceAsStream("/configfilename.properties");
讀取jar包外配置文件:
- String filePath = System.getProperty("user.dir") + "/conf/configfilename.properties";
- InputStream in = new BufferedInputStream(new FileInputStream(filePath));
另外,如果app中使用到log4j.properties文件,默認的存放路徑是src/log4j.properties,同上面一樣,我想把log4j.properties放在其他目錄中,這樣一來,在修改log4j配置文件的時候無需重新打jar包。
在main函數第一行添加如下代碼:
- PropertyConfigurator.configure(System.getProperty("user.dir") + "/conf/log4j.properties");