0

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. Could you explain what you mean by putting the properties in classpath I'm new to java development. I am using a build tool, but it's proprietary and not Maven.
If you're using a proprietary build tool, then I don't know how you'd do this, other than putting your properties file in the same directory as your code. And even that may not work.
0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.