Reputation: 3055
I'm using log4j for my logging purposes. To configure everything, I've made a log4j.xml that is outside of the jar-file. It works great, but gives problems when the jar-file isn't executed from the same directory where the log4j.xml is.
Example: jar-file is in /opt/myapp/test.jar
user@host:/opt/myapp$ java -jar test.jar
works great, but when I try this:
user@host:~$ java -jar /opt/myapp/test.jar
I get an error that log4j.xml cannot be found. That's because it is looking for it in my current working directory.
I also have a properties file that I use in my application. This file is in the config/ directory where the jar-file is, so /opt/myapp/config in this example. The same issue like the one above occurs when trying to load the config file.
How can I let Java load a file from the directory where the jar-file is (no matter from where the jar is executed)?
Probably something very easy, but I can't figure it out :(
Upvotes: 2
Views: 1791
Reputation: 11909
Specify using log4j system property, add this before that "-jar" part of the command: -Dlog4j.configuration=/opt/myapp/log4j.xml
Add the directory to the classpath, add this before that "-jar" part of the command:
-cp /opt/myapp/
You can specify the log4j.xml file manually in code and then reference it relative your jar file.
String path = ... ; PropertyConfigurator.configure(path);
Upvotes: 0
Reputation: 36229
Try:
java cp /opt/myapp/someohter.jar -jar /opt/myapp/test.jar
Use properties, to specify yourself, where to look for config files, for resources and such (as Paulo pointed out).
It is usually a bad idea to put such files close to the jar.file and make execution depending on the place from where you start. Often the directory, where an application is installed (the jar) is write protected for users, but config files are made to be editable.
Upvotes: 0
Reputation: 75356
The most reliable way to do this is to ask the JVM where the byte code for a given class came from.
See http://www.exampledepot.com/egs/java.lang/ClassOrigin.html for this snippet:
// Get the location of this class
Class cls = this.getClass();
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL loc = cSource.getLocation(); // file:/c:/almanac14/examples/
When loaded from inside a JAR you need to do a bit more post-processing.
Upvotes: 0
Reputation: 22296
You need to pass the file with the command line argument -Dlog4j.configuration=/path/to/file.
Check the manual if you need more options.
Upvotes: 1