【问题标题】:Error in specifying the location of property and log files指定属性和日志文件的位置时出错
【发布时间】:2019-11-05 15:21:01
【问题描述】:

我已经编写了一个代码来向 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

运行 jar 时出现以下错误

error in loading log4j prop file
config file not loaded

【问题讨论】:

  • 你可以从实际抛出的异常中获取更多信息,使用e.printStackTrace(System.err);而不是System.out.println("error in loading log4j prop file");

标签: java maven maven-3 maven-plugin maven-assembly-plugin


【解决方案1】:

我猜你的问题与 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 2014-01-06
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多