views:

303

answers:

2

Hi

I have a java application "app" which has a dependency of "dep.jar". "dep.jar" has a configuration file - "conf.properties" which is copied and packaged into dep.jar. The problem is that during running of "app", "conf.properties" cannot be found.

how should I specify the path to "conf.properties" (in the code of "dep.jar") so that it will be found on runtime?

Ronen.

To be more specific: I do not need the file as InputStream but I need the path to the file. specifically I need it to configure JMX:

HashMap<String, Object> env = new HashMap<String, Object>();
...
env.put("jmx.remote.x.password.file", "password.properties");

Where the "password.properties" is the configuration file needed at runtime. This code is in the jar file and not in the application. the "password.properties" is located in the jar file after I put it in the resources but how do I access it in runtime?

+2  A: 

That depends on how you try to load the file. If you use Class.getResourceAsStream(), the path is relative to the class on which you invoke getResourceAsStream(). To get to the "root", put a "/" in front of the file name:

InputStream in = Class.class.getResourceAsStream("/conf.properties");

[EDIT] If you need the path of the file (even when it's in a JAR), you can use getResource() which returns an URL. Use new File(url.toURI()) to get a path from the URL.

Aaron Digulla
see my edited question
rperez
In that case, use the URL. See my edit.
Aaron Digulla
A: 

Where are you defining conf.properties in dep.jar?

If the project is a jar project (has no declared packaging element or <packaging>jar</packaging>)

If your conf.properties is defined in or below the src/main/resources folder of the "dep" project, it will be output to the final jar.

for example, the file defined in:

src/main/resources/config/conf.properties

would be packaged in the jar in

config/conf.properties

Say you have a class com.foo.Bar and you want to access the properties file for it via:

InputStream stream = Bar.getClass().getResourceAsStream("conf.properties");

Then the file conf.properties would be defined under the folder:

src/main/resources/com/foo/conf.properties

If you want to access the resource stream from the root of the jar you'd do as Aaron's answer suggests:

InputStream stream = Bar.getClass().getResourceAsStream("/conf.properties");

and the resource would be defined in

src/main/resources/conf.properties
Rich Seller
see my edited question
rperez