我已经编写了将消息发送到MQ的代码,并且正在使用log4j记录结果。
因此,我有2个属性文件,一个将写入日志的日志文件和3个jar文件。
我所有的属性文件和输出日志文件都在src / main / resources中,而我的主类(源代码)在src / main / java中。
我的代码是:
try {
istream = new FileInputStream("log4j.properties");
Prop.load(istream);
istream.close();
} catch (Exception e) {
System.out.println("error in loading log4j prop file");
}
try {
Properties pro = new Properties();
String filename = "config.properties";
InputStream is = new FileInputStream(filename);
} catch (Exception a) {
System.out.println("config file not loaded");
}
我的POM是
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.ibm.Mq</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
但是当在我的Java代码中时,我指定配置文件的完整路径,例如“ C:/users/files/config.propertues”
它工作正常。但是我不希望发生这种情况,因为如果我在linux或任何其他环境中运行它,它将再次给出错误。
我使用以下命令打包我的罐子
mvn clean package assembly:single
运行罐子时出现以下错误
error in loading log4j prop file
config file not loaded
最佳答案
我想您的问题与maven和assemnly-plugin
无关,但是应该缩小到如何从类路径加载文件的范围。
由于将所有属性文件都放在了resources
文件夹中,因此在代码中使用它们的正确方法是:
try {
istream = this.getClass().getClassLoader()
.getResourceAsStream("log4j.properties");
Prop.load(istream);
istream.close();
} catch (Exception e) {
System.out.println("error in loading log4j prop file");
}
try {
Properties pro = new Properties();
String filename = "config.properties";
InputStream is = this.getClass().getClassLoader()
.getResourceAsStream(filename);
} catch (Exception a) {
System.out.println("config file not loaded");
}
请注意,传递给
#getResourceAsStream
的路径是相对于resources
文件夹的。进一步了解this thread。