我已经编写了向MQ发送消息的代码,并且我正在使用log4j来记录结果。
因此,我有两个属性文件,一个日志文件和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或任何其他环境中运行它,它将再次给出错误。
我使用下面的命令来打包我的jar
mvn clean package assembly:single当我运行我的jar时,我得到了下面的错误
error in loading log4j prop file
config file not loaded发布于 2019-11-06 14:58:48
我猜您的问题与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的更多信息,请阅读。
https://stackoverflow.com/questions/58714426
复制相似问题