Reputation: 195
I have a properties file that I've included within a jar I'll be distributing. Before I decided to include the file within the jar I was loading it like
properties.load(new FileInputStream(configFileName));
But this stopped working once the file was placed inside the jar so I changed the code to
properties.load(MyClass.class.getResourceAsStream(configFileName));
Only problem is I have unit tests that use my properties (which are loaded statically so I can't mock it). The unit tests are run before the jar is made so they all fail now. Is there an elegant way to handle a file that will be in a jar only if the program is run as a jar?
Upvotes: 0
Views: 216
Reputation: 7388
the problem probably is that this file is not visible to your classloader..
i'd use this
Classloader cl = getClass().getClassloader();
properties.load(cl.getResourceAsStream(configFileName))
pay attention to your classload if this app is a webapplication.. you'll have many classloaders on this case.. your resource must be visible to this classloader.. in a servlet container like tomcat they work this way
Bootstrap
|
System
|
Common
/ \
Webapp1 Webapp2 ...
you can read more here http://tomcat.apache.org/tomcat-6.0-doc/class-loader-howto.html
Upvotes: 0
Reputation: 678
If you happy to have the properties file live with your source code then try:
properties.load(getClass().getResourceAsStream("my.properties"));
The my.properties
file will have to live in the same package as the .java
file in this case.
Upvotes: 0
Reputation: 46
One way to do this is call getResourceAsStream()
, and if it returns null call new FileInputStream()
.
But a better question is: why aren't the properties in your classpath when you run unit tests? If you're using a build tool like Maven, then this should be automatic. And it would give a better sense that you're actually building what you think you are.
Upvotes: 1