指定属性和日志文件的位置时出错

我写了一个代码将消息发送到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或任何其他环境中运行它,它将再次给出错误。

我使用以下命令打包jar

 mvn clean package assembly:single

我跑罐子时遇到错误

error in loading log4j prop file
config file not loaded
tyh012 回答:指定属性和日志文件的位置时出错

我想您的问题与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://www.f2er.com/3158445.html

大家都在问