时间有限,不作排版和具体讲述问题产生的过程,下面是个人解决方案,已证明有效,其中Log4jP = "log4j.properties"java
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(); } }
参考内容 以下
app
转自 http://jrails.iteye.com/blog/1705464
函数
通常在项目中使用properties配置文件的时候都将相关的properties文件放在src目录下,在将该app打包生成jar后,相应的properties配置文件生...this
通常在项目中使用properties配置文件的时候都将相关的properties文件放在src目录下,在将该app打包生成jar后,相应的properties配置文件生成在jar包中,这样的话要修改配置文件又要从新打jar包,那是至关的麻烦。 spa
既然这么麻烦,你确定想将配置文件放在其余的目录下,生成的jar包内不包含相应的配置文件,修改配置文件无需从新打包,没错,下面就是一种解决方案了。 code
读取jar包内配置文件:orm
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/configfilename.properties");
读取jar包外配置文件:blog
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包。 get
在main函数第一行添加以下代码:it
PropertyConfigurator.configure(System.getProperty("user.dir") + "/conf/log4j.properties");