2012-05-24 65 views
9

在我的Java Swing应用程序我从属性加载log4j属性文件存储在应用程序包和我加载该属性文件,加载log4j属性

try {        
    PropertyConfigurator.configure("conf/log4j.properties"); 
    logger.info("Starting the system.");       

} catch (Exception e) { 
    e.printStackTrace(); 

} 

然后我获得以下错误当应用程序启动时,

log4j:ERROR Could not read configuration file [conf/log4j.properties]. 
java.io.FileNotFoundException: conf/log4j.properties (No such file or directory) 
     at java.io.FileInputStream.open(Native Method) 
     at java.io.FileInputStream.<init>(FileInputStream.java:138) 
     at java.io.FileInputStream.<init>(FileInputStream.java:97) 
     at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:297) 
     at org.apache.log4j.PropertyConfigurator.configure(PropertyConfigurator.java:315) 
     at com.bio.ofm.mnu.views.SplashScreen$1.run(SplashScreen.java:70) 
     at java.lang.Thread.run(Thread.java:722) 
log4j:ERROR Ignoring configuration file [conf/log4j.properties]. 
log4j:WARN No appenders could be found for logger (com.bio.ofm.mnu.views.SplashScreen). 
log4j:WARN Please initialize the log4j system properly. 

这种加载属性文件的方式是错误的吗?请帮忙。

我建立一个.jar文件,并使用该罐子**运行应用程序

+0

您的属性文件是存储在文件系统还是存储在JAR文件中?无论哪种情况,您使用的路径是否正确?您正在使用相对路径,这可能(并可能会)导致很多麻烦。 – Jochen

+0

我的属性文件是在罐子里 – Harsha

+0

看到迭戈的答案,应该工作。 – Jochen

回答

17

如果CONF是对源文件夹,您可以使用:

PropertyConfigurator.configure("classpath:conf/log4j.properties"); 

否则你可以试试这个:

PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("conf/log4j.properties")); 
3

LogManager自动类会查找名为的文件或log4j.xml中的classpath用于加载log4j类。直到版本1.2.6,log4j将只在类路径中查找log4j.properties文件。从版本1.2.7开始,log4j在类路径中查找log4j.propertieslog4j.xml

只需将log4j文件放在默认包中即可。您还应该确保该文件位于.class的目录中。

1

我用的是瑞秋Java库http://rachel.sourceforge.net/很多关于这种东西

下载的lib并将其添加到您的类路径。然后,您可以像使用它一样从JAR文件/包加载任何文件,并且在使用JNLP部署的应用程序时也可以使用它。他们有很多很好的教程来阅读加载文件的最佳方式。我通常喜欢将它们作为输入流加载。