1

I have written a code to send messages to MQ and i am using log4j to log the results.

So, I have 2 property files one log file where the logs will be written and 3 jar files.

All my property files and output log files are in src/main/resources and my main class(source code) is in src/main/java.

My code is:

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");
}

My POM is

<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>

But when in my java code i specify the the full path of config files like "C:/users/files/config.propertues" It works fine. But i dont want that to happen because if I run it in linux Or any other environment it will again give the error.

I used the below command to package my jar

 mvn clean package assembly:single

I got below error when I ran my jar

error in loading log4j prop file
config file not loaded
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Newbie
  • 45
  • 8
  • You can get more information from the actual exception being thrown, Use `e.printStackTrace(System.err);` rather than `System.out.println("error in loading log4j prop file");` – Sean Bright Nov 05 '19 at 15:44

1 Answers1

0

I guess your issue is not related to maven and assemnly-plugin but should be narrowed to how you can load a file from classpath.

Since you placed all properties files inside resources folder, the correct way to use them in your code is:

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");
}

Note that the path you pass to #getResourceAsStream is relative to resources folder.

Read more on this thread.

leopal
  • 4,711
  • 1
  • 25
  • 35