views:

126

answers:

3

I use this code snippet to obtain a file as an input stream. The file version.txt is packaged in my app's jar, in the upper-most folder.

InputStream resource = getClass().getClassLoader().getResourceAsStream("version.txt");

This works almost all of the time. But for one user, it's picking up another version.txt, that's not in my jar. How can I ensure that this loads the specific version.txt file that is in my jar?

+6  A: 

When you say, "upper-most folder", you mean the default package? If that's the case, you would have to ensure your JAR is earlier on the classpath than whatever is contributing the other version.txt file as Java searches along the classpath until it finds the first match.

Since it's hard to ensure your JAR would always be first, you should really place the version.txt file in a non-default package, such as:

com.yourcompany.yourproject.version

And then you'd need to modify the code to locate it:

Stream resource = getClass().getClassLoader().getResourceAsStream("com/yourcompany/yourproject/version/version.txt");

Using the default package is an anti-pattern.

hbunny
Oh boy. I call myself a Java expert, and yet I use this anti-pattern. I feel ashamed... :-) Preliminary testing has shown your solution to work!
Steve McLeod
As they say, failure is the best teacher ;-)
hbunny
+3  A: 

This is the danger inherent in putting things in the top-level package, you can pick up things you didn't really want to. This can be a benefit (like with log4j config, for example), but it's usually not what you want.

I strongly recommend putting your version.txt within your application's package structure, e.g. in com.myapp (or whatever your package name is), and then load it from there using

getClass().getClassLoader().getResourceAsStream("com/myapp/version.txt");
skaffman
A: 

the code snippet will use the class loader that loaded this class to find the version.txt file. if the file exists in the classpath used by the classloader in more than one place, it may return the wrong file (depending on the classpath order).

Omry