Using relative paths in java.io.File
is fully dependent on the current working directory. This differs with the way you execute the JAR. If you're for example in /foo
and you execute the JAR by java -jar /bar/jar/Bar.jar
then the working directory is still /foo
. But if you cd
to /bar/jar
and execute java -jar Bar.jar
then the working directory is /bar/jar
.
If you want the root path where the JAR is located, one of the ways would be:
File root = new File(Thread.currentThread().getContextClassLoader().getResource("").toURI());
This returns the root path of the JAR file (i.o.w. the classpath root). If you place your resource relative to the classpath root, you can access it as follows:
File resource = new File(root, "filename.ext");
Alternatively you can also just use:
File resource = new File(Thread.currentThread().getContextClassLoader().getResource("filename.ext").toURI());