ClassLoader loading wrong file

classloader, java

Solution

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.

Problem

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?

Original source